我正在参加 1z0-808 考试,许多有关异常处理的问题都出现在“抛出”和“try-catch” block 一起使用的情况下。
我想知道“throws”一起使用时如何影响“try-catch” block 的输出。
到目前为止我的理解是:
- “try-catch” block 将处理异常并执行您在“catch” block 中定义的任何代码。
“抛出”声明一个异常,并将异常处理责任转移到堆栈上。例如:
public class Test{ static void test() throws Exception{ throw new Exception(); } public static void main(String[] args) throws Exception{ test(); // A stack trace is printed } }
使用“try-catch”和“throws”。例如:
public class Test{ static void test() throws Exception{ try{ throw new Exception(); } catch(Exception e){ System.out.println("Handling is done"); } } public static void main(String[] args) throws Exception{ test(); // Outputs: "Handling is done" } }
如果异常由“try-catch” block 处理,那么使用“throws”是否有任何目的或效果?
最佳答案
Is there any purpose or effect in using "throws" if the exception is handled by the "try-catch" block?
是的。
我可以捕获从 Java 抛出的默认 Exception
,例如 IllegalArgumentException
,并且可以重新抛出一些有意义的自定义异常。
因此,当您从 catch block 中重新抛出具有更多详细信息的异常时,这是有意义的。
public void doLogin() throws NiceUserException {
try {
//To Do
} catch(IllegalArgumentException e) {
throw new NiceUserException("Hey! You forgot to pass your username");
}
}
关于java - 当一起处理和声明异常时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48610080/