【发布时间】:2015-07-20 08:13:45
【问题描述】:
import java.util.Scanner;
public class Test{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
String str = input.next();
int a;
try{
try{
a = Integer.parseInt(str);
}
catch(NumberFormatException nfe){
throw new CustomException("message");
}
if (a>50) throw new CustomException("message");
}
catch(CustomException e){
//do something
}
}
}
如果str 不是数字,parseInt 将抛出一个NumberFormatException。但我想“转换”它,这样我就会有一个带有“消息”的CustomException。我可以不使用上面的嵌套 try/catch 块来执行此操作吗?
【问题讨论】:
-
这是您的确切用例吗?如果是这样,那么您不需要做任何事情,您可以捕获 NumberFormatException。
-
if (a>50) throw new CustomException("message")?? -
你的意图是什么?闻起来像XY-problem。也许您可以将
CustomException替换为IllegalArgumentException。 -
在继续之前先看看“异常链”。在我写这篇文章时的答案是垃圾。
-
@Turing85 err...是的也许...但我只是想知道我是否可以在 catch 块中重新抛出异常并在方法中处理重新抛出的异常而不使用嵌套的 try/catch块。
标签: java exception exception-handling nested try-catch