LeoFaye 2017-11-19 10:46 采纳率: 0%
浏览 1741

为什么for循环中的异常没有被捕获到呢?

这是java多线程编程核心技术上的事例,书上是把try写在for循环外面,能够捕获到
异常,但我把try写到for里面后,发现捕获不到异常
public class MyThread extends Thread {

/*@Override
public void run() {
    try {
        for (int i = 0; i < 500000; i++) {
            if (this.interrupted()) {
                System.out.println("已经是停止状态了!我要退出了!");
                throw new InterruptedException();
            }
            System.out.println("i=" + (i + 1));
        }
    } catch (InterruptedException e) {
        System.out.println("catch interruted exception");
        e.printStackTrace();
    }
}*/


public void run() {

        for (int i = 0; i < 500000; i++) {
            try {
            if (this.interrupted()) {
                System.out.println("已经是停止状态了!我要退出了!");
                throw new InterruptedException();
            }
            System.out.println("i=" + (i + 1));
            } catch (InterruptedException e) {
                System.out.println("catch interruted exception");
                e.printStackTrace();
            }
        }
}


public static void main(String[] args) {
    try {
        MyThread t = new MyThread();
        t.start();
        Thread.sleep(2000);
        t.interrupt();
    } catch (InterruptedException e) {
        System.out.println("主线程被捕获");
        e.printStackTrace();
    }

}

}


  • 写回答

2条回答 默认 最新

  • Michaeldong1979 2017-11-19 11:09
    关注

    你是多线程程序,你捕捉的异常不是在你的所在的线程中,所以捕捉不到

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog