为什么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();
    }

}

}


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

你需要在发生Exception时加一个break或return



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