42

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?

2
  • 7
    e.getClass()? Or what do you mean by situation and instance name? Commented Sep 11, 2015 at 8:56
  • 4
    Are you asking for the Exceptions class name? Call e.getClass().getSimpleName() then. Commented Sep 11, 2015 at 9:09

5 Answers 5

77

Here you go:

try {
    throw new ArithmeticException();
} catch (Exception e) {
    System.out.println( e.getClass().getCanonicalName()); 
}

Output:

java.lang.ArithmeticException 
Sign up to request clarification or add additional context in comments.

Comments

22

The type of the exception is shown as part of the output of:

e.printStackTrace();

To get it programmatically you can use:

String exceptionClassName = e.getClass().getName();

It is poor form to have logic depending on exception sub types within a catch block. Sonar will flag this as a code violation (squid S1193).

Instead you should add multiple catch blocks to catch different types of exceptions:

try {
    readFile(fileName);
}
catch (java.io.IOException e) {
    LOG.error("Error accessing file {}", fileName, e);
}
catch (java.lang.IllegalArgumentException e) {
    LOG.error("Invalid file name {}", fileName, e);
}

Note: Since Log4j 2 (and SLF4J 1.6+) you can add a throwable as the last parameter and it will be recognized as such. So the above will work!

Since Java 7 you can also do a multi-catch:

}
catch (java.io.IOException | java.lang.IllegalArgumentException e) {
    LOG.error("Could not read the file {}", fileName, e);
}

The benefit of the multi-catch is that you can handle multiple exception types within a single catch block without having to revert to a common super class (like java.lang.Exception) that would include exception types you didn't want to handle.

Comments

4

Default exception logging is something like

try
{
//
}
catch (Exception e)
{
e.printStackTrace();
}

This will print the stacktrace of the exception to system.err

Comments

4

If you are looking to add some contextual information, you can take a look at Apache Commons ContextedRuntimeException

public static void main(String[] args) {
    try {
        doSomething();
    } catch (ContextedRuntimeException e) {
        System.out.println(e.getMessage());
        System.out.println(e.getContextEntries());
    }
}

private static void doSomething() {
    int divisor = 0;
    int dividend = 100;
    int result;
    try {
        result = dividend / divisor; // Just throw an exception to test things....
        System.out.print("DIVISION RESULT: "+result);
    } catch (ArithmeticException e) {
        throw new ContextedRuntimeException("Oops..division by zero not allowed", e)
        .addContextValue("Divisor", divisor)
        .addContextValue("Dividend", dividend);
    }
}

would output:

Oops..division by zero not allowed
Exception Context:
    [1:Divisor=0]
    [2:Dividend=100]
---------------------------------
[(Divisor,0), (Dividend,100)]

Comments

0

Like @user1438038 said in the comments of this question, you can use e.getClass().getSimpleName() to get the exception name, for example:

try {
    Double x = 1 / 0; // ArithmeticException
}
catch (Exception e) {
    System.out.println(e.getClass().getSimpleName()) // Will print "ArithmeticException"
}

If you want to get java.lang.ArithmeticException (to follow our example), you can use e.getClass().getConicalName():

try {
    Double x = 1 / 0; // ArithmeticException
}
catch (Exception e) {
    System.out.println(e.getClass().getConicalName()) // Will print "java.lang.ArithmeticException"
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.