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.
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.
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