Custom Exception类每次显示Unreachable catch块 [英] Custom Exception class shows Unreachable catch block everytime
本文介绍了Custom Exception类每次显示Unreachable catch块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
public class MyException extends Exception {
private static final long serialVersionUID = -2151515147355511072L;
private String message = null;
public MyException(){
super();
}
public MyException(String message){
super(message);
this.message = message;
}
public MyException(Throwable cause){
super(cause);
}
@Override
public String toString(){
return message;
}
@Override
public String getMessage(){
return message;
}
}
但是当我尝试使用这个类时,如下所示,它给出编译时错误。
try {
System.out.println(this);
} catch(MyException e){
// TODO:handle exception
}
编译时间错误:
MyException无法访问的catch块。我的问题是如果我正在扩展Exception class& amp; ;在所有构造函数中调用super,那么为什么会发生这个错误?解决方案显然,你没有做任何会生成一个 MyException
。首先写一个带有签名的方法抛出MyException
,调用它,然后你的问题解决了。这是一个例子:
public void someMethod()throws MyException
{
// some condition here 。
// if met ..
throw new MyException(cause);
}
,并将您的主要代码修改为:
try {
someMethod();
System.out.println(this);
} catch(MyException e){
// TODO:handle exception
}
I've created a custom Exception class that I want to use in my application:
public class MyException extends Exception {
private static final long serialVersionUID = -2151515147355511072L;
private String message = null;
public MyException() {
super();
}
public MyException(String message) {
super(message);
this.message = message;
}
public MyException(Throwable cause) {
super(cause);
}
@Override
public String toString() {
return message;
}
@Override
public String getMessage() {
return message;
}
}
But when I try to use this class, like below, it gives a compile time error.
try {
System.out.println("this");
} catch (MyException e) {
// TODO: handle exception
}
Compile time error:
Unreachable catch block for MyException . This exception is never thrown from the try statement body
My question is if I'm extending Exception class & calling super in all constructors, then why this error is occurring?
解决方案 Obviously, you are not doing anything that'd generate a MyException
. First write a method with the signature throws MyException
, call it and then your problem is solved. Here is an example:
public void someMethod()throws MyException
{
//some condition here.
//if met..
throw new MyException("cause");
}
and modify your main code as:
try {
someMethod();
System.out.println("this");
} catch (MyException e) {
// TODO: handle exception
}
这篇关于Custom Exception类每次显示Unreachable catch块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文