【发布时间】:2019-06-23 23:35:18
【问题描述】:
在下面的代码sn-p中,存在进程无法处理NullPointerException和IllegalStateException的情况。即在我有输入值val=-4 或val=-2 的情况下。
我读到在方法签名后添加throws 会有所帮助。但是,如果我将提到的值传递过来,代码仍然会中止。
public class Test extends Throwable{
public static void processA(int val ) throws NullPointerException, IllegalStateException{
try{
System.out.println("1");
processB(val);
}catch(ArithmeticException e){
System.out.println("2");
}
System.out.println("3");
}
public static void processB(int val) throws NullPointerException, IllegalStateException{
try{
System.out.println("4");
processC(val);
}catch(NullPointerException e){
System.out.println("5");
processC(val+4);
}finally{
System.out.println("6");
}
System.out.println("7");
}
public static void processC(int val)throws NullPointerException, IllegalStateException, ArithmeticException{
System.out.println("8");
if(val<1) throw new NullPointerException();
if(val==1) throw new ArithmeticException();
if(val>1) throw new IllegalStateException();
System.out.println("9");
}
public static void main(String[] args) throws Exception {
processA(1); //processA(-2) or processA(-4)
}
}
【问题讨论】:
-
如果 val
-
你想达到什么目的?只有使用“1”作为参数,您的代码才能正确完成
-
无论如何,你可以在这里阅读一下 RuntimeExceptions:stackoverflow.com/questions/22996407/…
-
在一张旧幻灯片上,我找到了这个示例,其中必须解释通过代码的流程是什么样的。在方法的签名之后还有一个使用 `throw NullPointerException, IllegalStateException' 的注释。但我为什么要使用它?我可以理解,正确的版本会使用多个捕获块来处理所有异常。
-
@Susliks - “但我为什么要使用它?” -- 这将表明调用者需要处理该方法抛出的异常。现在调用者可以通过
try-catch块来处理它,或者它可以将异常重新抛出给 its 调用者。编译器也会给你一个错误,说应该处理异常,但这只会发生在 checked 异常中。你抛出的是 unchecked 异常。这意味着在您的情况下,您几乎可以从方法声明中忽略它们。
标签: java exception-handling try-catch runtimeexception throws