Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java异常处理_Java_Multithreading_Runnable - Fatal编程技术网

Java异常处理

Java异常处理,java,multithreading,runnable,Java,Multithreading,Runnable,我想讨论的一件事是,当线程中的run方法主体中发生异常时,异常将反映在哪里(调用者)以及如何处理 这是我的密码: class MyThread extends Thread{ public void run() throws IllegalInterruptedException{ Thread.currentThread().sleep(1234); } } 然后谁(调用方)将管理此异常。如果我理解得很好,您希望能够处理在另一个线

我想讨论的一件事是,当线程中的run方法主体中发生异常时,异常将反映在哪里(调用者)以及如何处理

这是我的密码:

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

然后谁(调用方)将管理此异常。

如果我理解得很好,您希望能够处理在另一个线程中触发的异常。查看setDefaultUncaughtExceptionHandler,一页包含示例:


当发生异常时,程序会抛出异常。有一个通用教程可用,但总结是,您的程序将在引发异常的类中搜索,希望找到处理异常的方法:可能是catch语句,如:

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() );

}
如果您的程序在抛出该语句的类中找不到catch语句,它将在父类中查找处理该语句的内容。请注意,当抛出异常时,子类所做的任何事情都会在抛出异常时停止。出于这个原因,您应该将可能引发异常的代码块括在“try”块中,然后在“finally”语句中执行您想要执行的任何内容,不管发生什么,它都会执行

上面链接的教程非常有用。

您可以像
main()
一样查看
run()
,并获得答案。 但我认为您不能重写
run()
并声明
新的非运行时异常。。因此,您将得到一个编译错误。

ps:我找不到非法中断异常,也许你想说中断异常有两种不同的情况:

  • JVM将异常传递给异常处理程序(如果已为ThreadGroup安装)
  • 否则JVM将处理它
示例程序:

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();  

注意:签出

还有一个选项-将任务设为可调用任务,并使用执行者提交。当您获得未来时,您将自动包装任何异常。

在其他地方也是一个有用的答案。您没有真正回答这个问题,即多线程环境中异常会发生什么情况(即,哪个线程获得异常以及异常如何传播)。此外,异常不会在父类中得到处理,而是会进入调用链.thanx,但我可以将其用作uncheckedException。未检查的异常是扩展RuntimeException的异常。我将选中的异常称为非运行时异常。