开发者

Java-Exception Handling

I would like to discuss one thing is that , when an exception is occurred in the body of run method in thread then where it will be reflected(Caller) and how to handle this.

here is my c开发者_StackOverflowode:

class MyThread extends Thread{
        public void run() throws IllegalInterruptedException{
               Thread.currentThread().sleep(1234);
        }
}

then who(Caller) will manage this exception.


There are 2 different cases :

  • JVM passes the exception to an exception handler, if already installed for the ThreadGroup.
  • Otherwise the JVM handles it.

Sample program :

public class ThreadGroupDemo extends ThreadGroup {
    public ThreadGroupDemo() {
        super("This is MyThreadGroupDemo");
    }
    public void uncaughtException(Thread t, Throwable ex) {
        // Handle your exception here .... 
    }
}

Thread t = new Thread(new ThreadGroupDemo(), "My Thread") {
        // Some code here ......  
};

t.start();  

NOTE : Check out this link.


If I understood good you want to be able to handle exceptions that are fired in another thread. Take a look at setDefaultUncaughtExceptionHandler, one page with sample:

Java2S


You can see run() like main() and get yourself your answer. But I don't think you can override run() and declare new nonRuntime-Exceptions .. so you'll get a compile error.
ps: I can't find IllegalInterruptedException, maybe you wanna say InterruptedException


Exceptions are thrown by programs when something out of the ordinary occurs. A general tutorial is available here, but the summary is that your program will search within the class that throws the exception with hopes of finding something to handle it: probably a catch statement like:

catch (IllegalInterruptedException e) {

//what you want the program to do if an IllegalInterruptedException
//is thrown elsewhere and caught here. For example:

System.err.println( "program interrupted!" + e.getMessage() );

}

If your program can't find a catch statement in the class that throws the statement, it will look for something to handle it in a parent class. Be aware that whatever the child class was doing when an exception is thrown stops when it throws an exception. For this reason, you should enclose the block of code that may throw an exception in a 'try' block, and follow it with whatever you want to have execute in a 'finally' statement, which will execute no matter what.

The tutorial linked above is really helpful.


Yet another option - make the task a Callable and use Executors to submit it. You'll then get any exceptions wrapped automatically when you get the Future.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜