【问题标题】:Catch empty String. Which exception to use?捕获空字符串。使用哪个例外?
【发布时间】:2015-03-31 10:24:40
【问题描述】:

正如标题所示,我正在尝试捕获一个空字符串。我有一个类(我试图创建的对象的类),当字符串为空或空时抛出异常(检查 str.isEmpty)。 当我尝试在另一个类中使用空字符串创建对象时,它会按预期工作并引发异常。但是,我希望此类能够捕获该异常并通知用户。但它似乎永远不会捕获异常,即使我尝试编写 Catch(Exception exc)。 现在我知道 null 或空字符串不是非法的。但我的意图是对象类应该做到这一点。相反,似乎 catch 块根本不在乎。我开始认为我必须创建自己的某种异常类......或者我缺少什么?以下是代码的相关部分:

对象类构造函数:

    public Valueables(String name){
    //name.trim().length() == 0
    if(name == null || name.isEmpty()){
        try {
            throw new Exception("Subclasses of Valueables cannot take in an empty String or null value for the \"name\" constructor");
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(2);
        }
    }
    else
        this.name = name;
}

另一个类(新的 Trinket 对象是 Valueables 的子类。上面有构造函数代码的那个):

while(loopPassErrorControl == false){

                        //I don't think the try loop is relevant. But just to make sure...
                        //Otherwise just ignore it

                        try{
                            TrinketForm Tform = new TrinketForm();
                            answer = JOptionPane.showOptionDialog(ValueablesFrame.this, Tform, "Nytt smycke", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,
                                    null, options , null);
                            if (answer != JOptionPane.OK_OPTION){
                            return;
                            }

                            valueablesList.add(new Trinket(Tform.getName(), Tform.getGemstones(), Tform.getMetalSelected()));
                            loopPassErrorControl = true;

                        }catch(NumberFormatException | NullPointerException exc) {
                        JOptionPane.showMessageDialog(ValueablesFrame.this, "Något gick fel");
                        }
                        }
                        //Test
                        for(Valueables obj : valueablesList){
                        System.out.println(valueablesList);
                        }

【问题讨论】:

  • 如果是非法参数,为什么不IllegalArgumentException
  • 您知道不必抛出和捕获异常即可打印其堆栈跟踪吗? new Exception("message").printStackTrace(); 也可以。
  • 你在哪里打电话new Valueables(name)
  • 你的 try catch 没有意义:你抛出一个异常并立即捕获它并退出系统。另外,我们不知道 Trinket 的代码是什么。
  • 您应该检查name.trim().isEmpty().trim() 删除前导和尾随空格)而不是name.isEmpty(),因为.isEmpty()documented 作为Returns true if, and only if, length() is 0. .因此,如果名称仅包含空格,则检查未修剪的名称可能会允许它通过。

标签: java swing exception


【解决方案1】:

首先在 Valuable 上抛出 RuntimeException:

public Valueables(String name){
    //name.trim().length() == 0
    if(name == null || name.isEmpty()){
        throw new RuntimeException("Subclasses of Valueables cannot take in an empty String or null value for the \"name\" constructor");

    }
    else
        this.name = name;
}

并且不要捕获异常。

其次,在另一个类上捕获一个 RuntimeException 并显示一条消息:

...}catch(RuntimeException exc) {
                        JOptionPane.showMessageDialog(exc.getMessage());
                    }

希望对你有所帮助!

【讨论】:

  • 是的!我现在看到我在我的对象类中有机会在框架类facepalm 中捕获它之前捕获了异常。非常感谢!
【解决方案2】:

已经提出了一个关于空字符串的问题,空字符串仍然不是空的,所以如果你想捕获它,它必须抛出“IllegalArgumentException”。

【讨论】:

    【解决方案3】:

    尝试将其捕获为通用异常,替换 NuumberFormatException 和 NullpointerException。

    您也可以在 Java 中执行此操作。

    try {
        //Some Code here
    } catch (NumberFormatException | NullPointerException ex) {
        //Handle NumberFormat and NullPointer exceptions here    
    } catch (Exception ex) {
        //Handle generic exception here
    }
    

    【讨论】:

    • 捕获Exception 是个坏主意,除非你很不幸地拥有抛出Exception 的代码——除非绝对必要,否则你应该避免编写它,因为它是相当于返回Object 的异常(它基本上不提供类型信息)。如果需要特定处理的新异常(例如InterruptedException)被添加到方法签名中,捕获Exception 是一种隐藏问题的绝妙方法。
    • 我提到我试过这个。它不起作用。另外,我想象用 Exception 捕获各种异常是丑陋的?因为我认为 Exception 是其他异常的超类,例如 NumberFormatException?
    猜你喜欢
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多