如何通过java中的exception捕获来读取子类异常消息


class Student {
public static Student getStudent(int id) throws StudentNotFoundException {
throw new StudentNotFoundException("Student not found");
}
public static void main(String... args){

try{
Student student = getStudent(1);
}catch(Exception e){
//want to print the exception message passed from getUser() method i.e. Student not found
}
}
}

如何通过使用exception捕获getStudent方法抛出的异常来打印它。?

e.printStackTrace();                  // print to error message and stack trace to standard error
System.out.println(e.getMessage());   // print only the message to standard output

要打印异常消息,请使用同名的e.getMessage()方法。

最新更新