我第一次使用 swing API 构建一个 GPA 计算器 Java 应用程序。这是我的第一个 GUI 应用程序。
我在以下情况下处理过3个异常
- 如果用户输入十进制值
- 如果用户输入负值
- 如果用户将文本字段留空。
我在 catch block 中使用了 return 关键字(特别是在 ArithmeticException 情况下),因为即使在显示错误消息后,程序仍在计算 GPA(我不希望这样)。
尽管代码按照我想要的方式工作正常,但使用代码中所示的 return
是否是解决我的问题的正确/良好方法?
代码:
try{
int temp;
temp = Integer.parseInt(c1.getText());
if(temp < 0){
throw(new ArithmeticException());
}
}
catch(NumberFormatException ex){
JOptionPane.showMessageDialog(null,"please fill the fields with proper values.");
return;
}
catch(ArithmeticException e){
JOptionPane.showMessageDialog(null,"negative values not allowed");
return;
}
最佳答案
我想说,返回语句完全取决于个人。有些人不喜欢它们,有些人喜欢。
就我个人而言,我喜欢它们,并且我发现它可以使代码更易于阅读。然而,有些人却有不同的感觉。您的替代方法是检查条件,将结果输出为 boolean 值,并且仅在 boolean 值与您期望的匹配时才运行代码。
此外,抛出异常会导致 java 比直接进行检查做更多的工作。
这会更干净:
try{
int temp;
temp = Integer.parseInt(c1.getText());
if(temp < 0){
JOptionPane.showMessageDialog(null,"negative values not allowed");
return;
}
}
catch(NumberFormatException ex){
JOptionPane.showMessageDialog(null,"please fill the fields with proper values.");
return;
}
关于java - 在catch block 中使用return?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52550692/