Reputation: 6521
I managed to bypass the try catch block, by nesting multiple threads.
Is therere some rule, where it is documented, when the try catch block is bypassed by Exceptions?
try{
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("Thread");
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
System.out.println("ThreadGUI");
throw new NullPointerException();
}
});
}
};
Thread t = new Thread(r);
t.start();
} catch(NullPointerException e) {
//nothing
}
System.out.println("Ende");
Upvotes: 0
Views: 401
Reputation: 500167
Exceptions don't automatically propagate across thread boundaries. If you throw an exception in a particular thread, you can only catch it in that thread. The lexical structure of your code makes no difference in this respect.
The following are the relevant parts of the JLS:
During the process of throwing an exception, the Java virtual machine abruptly completes, one by one, any expressions, statements, method and constructor invocations, initializers, and field initialization expressions that have begun but not completed execution in the current thread. This process continues until a handler is found that indicates that it handles that particular exception by naming the class of the exception or a superclass of the class of the exception (§11.2). If no such handler is found, then the exception may be handled by one of a hierarchy of uncaught exception handlers (§11.3) - thus every effort is made to avoid letting an exception go unhandled.
...
If no
catch
clause that can handle an exception can be found, then the current thread (the thread that encountered the exception) is terminated.
Upvotes: 4
Reputation: 4640
Your exception is thrown out in a different thread. This is why it is not caught. You might want to catch it inside tyour new thread and somehow propagate it to the main one.
Upvotes: 0