Java 捕获空字符串。使用哪个异常?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29366366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 07:52:02  来源:igfitidea点击:

Catch empty String. Which exception to use?

javaswingexception

提问by user3130840

As the title suggests I am trying to catch an empty String. I have a class (the class of the object I am trying to create) that throws an Exception when the String is null or empty (check with str.isEmpty). When I try to create the object with an empty String in another class it works as intended and throws an Exception. However, I want this class to Catch that Exception and notify the user. But it never seems to Catch the Exception, even if I try to write Catch(Exception exc). Now I know a null or empty String is not illegal. But my intention was that the object class was supposed to make it so. Instead it seems as if the catch block doesn't care at all. I am starting to think that I would have to create my own exception class of some sort... or is there something I am missing? Here are the relevant parts of the code:

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

The object class constructor:

对象类构造函数:

    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;
}

The other class (the new Trinket object is a subclass of Valueables. The one with the constructor code above):

另一个类(新的 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);
                        }

回答by Alvin Magalona

try to catch it as the generic Exception, replace the NuumberFormatException and NullpointerException.

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

You can also do this in Java.

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

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

回答by vathek

First throw a RuntimeException on Valuable:

首先在 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;
}

And do not catch the exception.

并且不捕获异常。

Second, on the other class catch a RuntimeException and show a mesage:

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

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

Hope helped you!

希望对你有帮助!

回答by Goty Metal

Already made a question about empty strings, an empty string is still not null so it must throw "IllegalArgumentException" if you WANT to catch it.

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