我想重现 InterruptedException 行为的一部分,但我不明白它是如何工作的......
所以我有这个代码:
public static void main(String [] args){
try{
}catch(InterruptedException ie){
}
}
当我尝试编译它时,出现此编译器错误
Unreachable catch block for InterruptedException. This exception is never thrown from the try statement body
我创建了一个自定义异常,它并不是真正的异常,因为它没有扩展异常...
class MyException extends Throwable{
}
public static void main(String [] args){
try{
}catch(MyException ie){
}
}
显示相同的编译器错误
Unreachable catch block for MyException. This exception is never thrown from the try statement body
然后我就这么做了
public static void main(String [] args){
try{
throw new MyException();
} catch(MyException e){
e.printStackTrace();
}
try{
throw new InterruptedException();
} catch(InterruptedException e){
e.printStackTrace();
}
}
它们都编译得很好。
但现在棘手的部分来了..
public static void main(String [] args){
try{
throw new MyException();
} catch(Exception e){
e.printStackTrace();
} catch(MyException e){
e.printStackTrace();
}
try{
throw new InterruptedException();
} catch(Exception e){
e.printStackTrace();
} catch(InterruptedException e){
e.printStackTrace();
}
}
编译器说
Unreachable catch block for InterruptedException. It is already handled by the catch block for Exception
你能告诉我 InterruptedException 如何显示“InterruptedException 无法访问的 catch block 。此异常永远不会从 try 语句主体中抛出”编译器错误并同时扩展 Exception,因为当我扩展异常时,我的自定义异常不会显示此编译器错误
举个例子:
class MyException extends Exception{}
public static void main(String [] args){
try{
}catch(MyException me){
}
}
此代码不会引发任何编译器错误
但是下面的代码可以
class MyException extends Throwable{}
public static void main(String [] args){
try{
}catch(MyException me){
}
}
最佳答案
发生这种情况是因为 InterrupedException
是 Exception
的子类,但 Exception
已被前面的 catch
捕获 block 。
It is a compile-time error if a catch clause can catch an exception class E1 and a preceding catch clause of the immediately enclosing try statement can catch E1 or a superclass of E1.
InterruptedException catch block 中的 block 将是无法访问的代码,这将是此编译器错误的原因。
关于Java 自定义异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33616837/