简体   繁体   English

捕获线程中的所有异常

[英]Catch all exceptions within a thread

Below is the code I have developed for a thread. 以下是我为线程开发的代码。

   int i;
    Thread thread = new Thread()
    {
        @Override
        public void run() {
            try {
                while(true) {
                    sleep(10000);
                    i++
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };

    thread.start();

Is there any possible way I can use any other catch or exception to catch all possible crushes within it? 有什么可能的方法可以使用其他捕获或异常捕获其中所有可能的暗恋? Thank you in advance! 先感谢您!

只需要catch (Exception ex)catch (InterruptedException e)

It seems that only exception that block can throw,you have already handled but for safer side you can catch parent exception too i,e (Exception e) as below : 似乎只有块可以抛出的异常,您已经处理过,但是为了更安全起见,您也可以捕获父异常,即(异常e),如下所示:

 try {
   //stuff
}
catch (InterruptedException e) {
     e.printStackTrace();
}
catch (Exception e) {
      e.printStackTrace();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM