Arafe Zawad Sajid Arafe Zawad Sajid - 1 month ago 12
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:

try{
//throws an IndexOutOfBoundsException during runtime
}catch(IndexOutOfBoundsException ex){
System.err.println(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

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

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

Demo.

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.

Comments