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
    关注

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

    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?