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 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突