Arafe Zawad Sajid Arafe Zawad Sajid - 1 year ago 87
Java Question

How to display a detailed error message using try{ }catch(){ } blocks

Suppose in your program you might get an IndexOutOfBoundsException. i am handling it in the following way:

//throws an IndexOutOfBoundsException during runtime
}catch(IndexOutOfBoundsException ex){

This will only display java.lang.IndexOutOfBoundsException. But I would like to display a detailed error message (which won't terminate the program), like the one that java gives us (lineNumber, fileName, etc) when we do not handle the error and thus terminates the program.

Answer Source

Use ex.printStackTrace() method to print the exception:

try {
    int[] x = new int[1];
    x[2] = 5;
} catch (IndexOutOfBoundsException ex) {
System.err.println("Program completed successfully");


If you are running in an environment where console output is not desirable, call ex.getStackTrace(), and display elements in a way that is consistent with the user interface of your program.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download