• 周六. 10 月 5th, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

Catching all exceptions in Java

King Wang

1 月 3, 2022

We are in the process of learning abnormality , You can write only one exception handler to catch all types of exceptions .

That is, by catching the base class of the exception type Exception That can be done :

catch(Exception e){
System.out.println("Caught an exception");
}

So we’ll catch all the exceptions , So it’s best to put it at the end of the handler list , To prevent it from catching exceptions before other handlers .

Let’s use a program to demonstrate :

public class ExceptionMethods {
public static void main(String[] args) {
try{
throw new Exception("My Exception");
}catch(Exception e){
System.out.println("Caught Exception");
System.out.println("getMessage():"+e.getMessage());
System.out.println("getLocalizedMessage():"+
e.getLocalizedMessage());
System.out.println("toString()"+e);
System.out.println("printStackTrace():");
e.printStackTrace(System.out);
}
}
}

Running results :

This provides a reference for you !

thank you !

发表回复