【发布时间】:2018-11-11 19:01:09
【问题描述】:
我构建了一些异常类(目前没有从任何类继承)。我想做一个“尝试”和“捕捉”,并在捕捉中打印与已抛出的特定异常类相关的错误消息。 有没有办法可以做
try(something){
}
catch(){
System.out.println(error.printMsg());
}
并且根据excpetion,它会打印与类相关的msg?
编辑:我将改进我的问题,在尝试和捕捉中,可以抛出一些我构建的可能的异常类,我想要而不是这样做:
catch(Error1){
System.err.println(Error1.ERROR_MSG);
}
catch(Error2){
System.err.println(Error2.ERROR_MSG);
}
要做的事情:
catch(ERROR1 | ERROR2){
System.out.println(GenarlError.ERROR_MSG)
// maybe to do a class that all the Excpetion will inhirt from, and somehow
//do upcasting,or something like that (but If I will do upcasting it would
//print the message or the right class?
}
【问题讨论】:
-
就像你写的一样..
-
为什么您的自定义异常没有扩展 RunTimeExceptions??
-
如果它们至少不继承
Exception类,你打算如何扔掉它们? -
不直接或间接继承
Throwable的类不能与try/catch一起使用。 -
@Henry 继承自
Throwable的类不一定是异常。