I would like to know what the exception instance was in this situation:
try { // some risky actions } catch (Exception e) { System.out.println("Get instance name there"); }
How can I achieve this?
To get it programmatically you can use: String exceptionClassName = e. getClass(). getName();
Using printStackTrace() method − It print the name of the exception, description and complete stack trace including the line where exception occurred. Using toString() method − It prints the name and description of the exception. Using getMessage() method − Mostly used. It prints the description of the exception.
The try-catch is the simplest method of handling exceptions. Put the code you want to run in the try block, and any Java exceptions that the code throws are caught by one or more catch blocks. This method will catch any type of Java exceptions that get thrown. This is the simplest mechanism for handling exceptions.
The Throwable class provides the following three methods to print the exception message: Using printStackTrace Method. Using getMessage() Method. Using toString() Method.
Here you go:
try { throw new ArithmeticException(); } catch (Exception e) { System.out.println( e.getClass().getCanonicalName()); }
Output:
java.lang.ArithmeticException
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With