Question

I have a try/catch thing set up where it will catch all exceptions and then display the error.

Here is my code:

try {
    //CODE THAT COULD ERROR HERE
} catch (final Exception e) {
    System.err.println("Unexpected error: " + e.getStackTrace()[0]);
}

The above code gives me the LAST class that had the error. How do I detect the LAST class of MY PROGRAM that had the error?

Example Output: "Unexpected error: package.ClassName.method(ClassName.java:46)"

I want it to output the line of my program that had the error, not the line of a built-in java class that error-ed because of my program.

Was it helpful?

Solution

e.printStackTrace()

might make you happier. Or print the top of the array of stack trace entries available from the appropriate method.

http://docs.oracle.com/javase/6/docs/api/java/lang/Throwable.html#getStackTrace()

returns them. The first one is what you are asking for.

OTHER TIPS

You can use getStackTrace to get an array of StackTraceElement instances, and filter that based on your package and/or class names (using getClassName for each element, which gives you the fully-qualified class name for that stack trace frame). That would let you winnow it down to your code rather than the JDK class the exception originated in.

        try {
            //error producing code
        } catch (Exception e) {
            for (StackTraceElement s : e.getStackTrace()) {
                if (!s.getClassName().startsWith("java.")) {
                    System.out.println("file name: " + s.getFileName());
                    System.out.println("class name: " + s.getClassName());
                    System.out.println("method name: " + s.getMethodName());
                    System.out.println("line number: " + s.getLineNumber());
                    System.out.println();
                    //break; // will be the highest non java package...
                }
            }
        }

You of course could switch it to be package specific so if (s.getClassName().startsWith("com.company")) { so it wont return for a third party library or something in the sun package or other non java package.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top