开发者社区> 问答> 正文

菜鸟关于Java中抛出异常和上抛异常的问题 报错

"

本人最近在学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); } } }

" ![image.png](https://ucc.alicdn.com/pic/developer-ecology/0dd305a61edc4585aa79b31b47ecd16b.png)

展开
收起
因为相信,所以看见。 2020-05-26 13:56:12 891 0
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(); //本行将报错,因为线程只能启动一次
        }
    }
    
    //本例中是将上抛异常和捕获异常写到多线程代码里面
    //目的是实现当i为8时手动抛出异常
    //基本上实现了,但是不知道为什么,三个线程处理了30条记录,不符合Runnable接口的共享资源特征
    //将在JavaTest22_06.java中重写程序,试图找出问题。
    
    
    
    
    ######

    别的线程是不能直接抛异常出去的,你想想线程本身就是异步的,你执行线程的时候,主线程的方法早就跑完了

    ######

    你要是用IDE工具的话 一准提示你 this.excepTest(i); Unhandled exception type Exception

    ######

    没看明白你想问什么。。。

    " ![image.png](https://ucc.alicdn.com/pic/developer-ecology/8ba587a88d1c4554aa5a9b953d1b42e6.png)
    2020-05-27 10:17:03
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载