Explain me how can you catch an exception thrown by another thread in Java?
Submitted by: MuhammadThis can be done using Thread.UncaughtExceptionHandler.
Here's a simple example:
// create our uncaught exception handler
Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread th, Throwable ex) {
System.out.println("Uncaught exception: " + ex);
}
};
// create another thread
Thread otherThread = new Thread() {
public void run() {
System.out.println("Sleeping ...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Interrupted.");
}
System.out.println("Throwing exception ...");
throw new RuntimeException();
}
};
// set our uncaught exception handler as the one to be used when the new thread
// throws an uncaught exception
otherThread.setUncaughtExceptionHandler(handler);
// start the other thread - our uncaught exception handler will be invoked when
// the other thread throws an uncaught exception
otherThread.start();
Submitted by: Muhammad
Here's a simple example:
// create our uncaught exception handler
Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread th, Throwable ex) {
System.out.println("Uncaught exception: " + ex);
}
};
// create another thread
Thread otherThread = new Thread() {
public void run() {
System.out.println("Sleeping ...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Interrupted.");
}
System.out.println("Throwing exception ...");
throw new RuntimeException();
}
};
// set our uncaught exception handler as the one to be used when the new thread
// throws an uncaught exception
otherThread.setUncaughtExceptionHandler(handler);
// start the other thread - our uncaught exception handler will be invoked when
// the other thread throws an uncaught exception
otherThread.start();
Submitted by: Muhammad
Read Online Java Software Engineer Job Interview Questions And Answers
Top Java Software Engineer Questions
☺ | Do you know how threadsafe is enum in Java? |
☺ | Explain me what is a good usecase of calling System.gc()? |
☺ | Explain me why doesn’t the following code generate a NullPointerException even when the instance is null? |
☺ | Do you know what is the advantage of generic collection? |
☺ | Tell us what do you mean by aggregation? |
Top Java Programming Language Categories
☺ | Core Java Interview Questions. |
☺ | Hibernate Interview Questions. |
☺ | Advanced Java Interview Questions. |
☺ | IBM WebSphere Interview Questions. |
☺ | Spring Framework Interview Questions. |