Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Exception type

Tags:

java

exception

If I have the following code:

try {
    //some offensive code     
} catch (Exception e) {
    String type = //get type of e
    Assert.fail(type + " thrown.");
}

Is there a way I can get the type of the Exception so I can output:

NullReferenceException thrown.
InvalidOperationException thrown.
OutOfMemoryException thrown.

etc? I know I can switch on different types using instanceOf(), but that assumes I'm expecting a specific type.

FWIW, I know this specific code chunk is terrible and violates many of the best practices suggested by Eric Lippert. I'm just curious if there is a way to determine Exception type at runtime.

like image 355
Devin Avatar asked Apr 19 '26 15:04

Devin


1 Answers

You can call e.getClass().getName() to get class name.

getName() returns the name including package, e.g. java.lang.OutOfMemoryError.

getSimpleName() returns just a class name, e.g. OutOfMemoryError.

See javadoc for Class object to see all info you can get.

like image 104
lopisan Avatar answered Apr 21 '26 05:04

lopisan