3

When i execute the below code,I am seeing the output as:

Finally

Exception in thread "main" java.lang.NullPointerException at ClientTestConcepts.main(ClientTestConcepts.java:9)

Who prints the bold faced statements.

public class ClientTestConcepts {
    public static void main(String []args){
        try{
            throw new NullPointerException();
        }
        finally{
            System.out.println("Finally");
        }
    }
}

2 Answers 2

7

The Java runtime.

It catches all exceptions not handled in user code, and prints them on the error output (by default).

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

1 Comment

@JavaUser, whatever you do in the catch block :-) If you catch it within main and do not rethrow it, the runtime will not see it.
3

Each thread has a default uncaught exception handler that runs when an exception makes it to the top of the stack. The one you are observing is provided by ThreadGroup.uncaughtException:

Called by the Java Virtual Machine when a thread in this thread group stops because of an uncaught exception, and the thread does not have a specific Thread.UncaughtExceptionHandler installed.

The uncaughtException method of ThreadGroup does the following: (...)
... a message containing the thread's name, as returned from the thread's getName method, and a stack backtrace, using the Throwable's printStackTrace method, is printed to the standard error stream.

If you want some other behaviour register an uncaught exception handler for the thread.

10 Comments

First of all, it's not the user that's using ThreadGroup. Second of all, that's what's happening. Whether it's obsolete or not (I would say it's not, since it's still very much used), it's what's causing the user behaviour now. Not some magic in the Java runtime.
BTW if anybody knows how to fix that link, I'd be delighted. It's interpreted correctly in the preview pane so I think it's a SO bug.
Well, the very quote says "Called by the Java Virtual Machine" ... so it may not be magic, but it is caused by the Java runtime :-)
@Peter: Called, yes. But it's not like it's printed in some native code. It's fully Java code provided in the runtime library that actually does the printing. And it's configurable.
I managed to fix the link by replacing the ' ' (space) in it with %20 :-)
|

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.