【发布时间】:2015-11-09 19:37:39
【问题描述】:
我想重现部分 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 块。这个异常永远不会从 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){
}
}
【问题讨论】:
-
错误消息说明了一切:“它已经由异常的 catch 块处理”。根据定义,捕获每个异常的东西都会捕获 InterruptedException。
-
我在问题的最后做错了。我想知道 InterruptedException 如何扩展 Exception 并且当它未在 try 主体中抛出时显示编译器错误,因为当我扩展异常时,我的自定义异常不会显示此编译器错误
-
编辑您的问题并把它弄清楚。我不明白你的意思。
-
因此,如果我设计一个类,在其中扩展 Exception 类以使其成为自定义异常,则当它未在 try 块中抛出时,我无法使其显示编译器错误。 class MyException extends Exception{} public static void main(String [] args){ try{ }catch(MyException me){ } },不显示任何编译器错误
-
拥有
MyException扩展Exception(或Throwable),加上在捕获MyException时有一个空的try块对我来说是编译器错误。
标签: java exception exception-handling try-catch interrupted-exception