Java中的异常,根据类打印msg

时间:2018-06-01 15:29:35

标签: java exception try-catch

我有一些我构建的异常类(目前不能从任何类继承)。我想做一个"尝试"并且"赶上"并在catch中打印与已抛出的特定Exception类相关的错误消息。 有可能的方法吗

try(something){
}
catch(){
   System.out.println(error.printMsg());
}

并且根据该重复,它将打印与该类相关的消息?

编辑:我将改进我的问题,在try和catch中,可以抛出我构建的一些可能的异常类,我想要而不是做:

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?
}

2 个答案:

答案 0 :(得分:1)

如果要捕获多个异常并对每个异常执行不同的操作,可以编写如下代码:

try {
    // Execute code
} catch(MyException e) {
    System.out.println(e.getMessage());
} catch(MyNextException e) {
    System.out.println(e.getMessage());
}

如果你想对每个例外做同样的事情,你可以更简洁地捕捉它们:

try {
    // Execute code
} catch(MyException | MyNextException e) {
    System.out.println(e.getMessage());
}

请注意,尽管您的例外情况需要以某种形式扩展Exception,但要执行此操作

答案 1 :(得分:0)

在catch块中,您必须具有异常类型:

public class Main throws Exception{
try{
  ...
}
catch(Exception error){
   System.out.println(error.printStackTrace());
}
}

如果你想制作自己的异常,可以扩展Exception类。并在你的主类上抛出异常