gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:44:07 24 4
gpt4 key购买 nike

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

对象类构造函数:

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

最佳答案

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

希望对你有帮助!

关于java - 捕获空字符串。使用哪个异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29366366/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com