本人最近在学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);
}
}
}
I found the problem, I threw an exception in the excepTest method, and then the exception was thrown on the method
The exception was thrown to the run method and the problem should be handled within the run method
But the search capture in the code is in the main method, so the exception will definitely not be caught
Corrected code:
Other threads cannot throw exceptions directly. If you think about it, the thread itself is asynchronous. When you execute the thread, the main thread's method has already finished running
If you use an IDE tool, it will definitely prompt you this.excepTest(i); Unhandled exception type Exception
I don’t understand what you want to ask. . .