Arafe Zawad Sajid Arafe Zawad Sajid - 2 months ago 24
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.


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.