开发者社区 问答 正文

关于Java中抛出异常和上抛异常的问题

尝试将两个知识合并起来写段代码,调试遇到问题,把这个这么简单的问题提到这里请不吝赐教,谢谢!

class Test22_05 implements Runnable{

    public void run() {
        for(int i = 0; i < 10; i++){
            this.excepTest(i);
            System.out.println(Thread.currentThread().getName() + ":i = " + i);
        }
    }

    public void excepTest(int i)throws Exception{
        if(i == 8){
                throw new Exception("这是手动抛出异常!");
            }
    }
}

public class JavaTest22_05{
    public static void main(String args[]){
        Test22_05 t1 = new Test22_05();
        Thread tt1 = new Thread(t1);
        Thread tt2 = new Thread(t1);
        Thread tt3 = new Thread(t1);
        tt1.setName("线程1");
        tt2.setName("线程2");
        tt3.setName("线程3");
        try{
            tt1.start();
            tt2.start();
            tt3.start();
        }catch(Exception e){
            System.out.println(e);
        }
    }
}

展开
收起
蛮大人123 2016-02-25 14:55:10 3048 分享 版权
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪

    excepTest方法中抛出异常,然后该方法上抛了异常该异常被抛给了run方法,应该在run方法内处理该问题
    但是代码中的查找捕获却在main方法中,肯定捕获不到异常

    class Test22_05 implements Runnable{
    
        public void run() {
            for(int i = 0; i < 10; i++){
                try{
                    this.excepTest(i);
                }catch(Exception e){
                    System.out.println(Thread.currentThread().getName() + "出现异常:" + e);
                }
                System.out.println(Thread.currentThread().getName() + ":i = " + i);
            }
        }
    
        public void excepTest(int i)throws Exception{
            if(i == 8){
                    throw new Exception("这是手动抛出异常!");
                }
        }
    }
    
    public class JavaTest22_05{
        public static void main(String args[]){
            Test22_05 t1 = new Test22_05();
            Thread tt1 = new Thread(t1);
            Thread tt2 = new Thread(t1);
            Thread tt3 = new Thread(t1);
            tt1.setName("线程1");
            tt2.setName("线程2");
            tt3.setName("线程3");
                tt1.start();
                tt2.start();
                tt3.start();
                tt1.start(); 
        }
    }
    2019-07-17 18:47:32
    赞同 展开评论
问答分类:
问答标签:
问答地址: