Thread中的异常处理

(1)CheckedException

                1.非线程解决方案

                    对于CheckedException,通常可以通过try、catch或者声明抛出异常throws Exception2种方式来处理异常

                2.线程解决方案

                    定义线程会重写run方法,而run方法的定义如下:

public interface Runnable {
    public abstract void run();
}
                   可以看出并没有声明抛出异常,所以我们不能通过声明抛出异常的方式来处理异常。

                   如果我们非要声明抛出

public class Task implements Runnable {

	@Override
	public void run() throws Exception {
		int number0 = Integer.parseInt("1");
		throw new Exception("Just for test");
	}
}
                  会发现连编译都无法通过
Task.java:3: error: run() in Task cannot implement run() in Runnable
    public void run() throws Exception {
                ^
  overridden method does not throw Exception
1 error
                 那么就只能通过try、catch方式解决

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class ThreadTest {  
    public static void main(String[] args) {  
    	MyTask task = new MyTask();  
        Thread thread = new Thread(task);  
          
        thread.start();  
    }  
} 

class MyTask implements Runnable {
	public void run() {
		try {
			FileInputStream fInputStream = new FileInputStream(new File("xx.pdf"));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
}
           结果为(xx.pdf文件不存在):

java.io.FileNotFoundException: xx.pdf (系统找不到指定的文件。)
	at java.io.FileInputStream.open(Native Method)
	at java.io.FileInputStream.<init>(FileInputStream.java:106)
	at my.MyTask.run(ThreadTest.java:20)
	at java.lang.Thread.run(Thread.java:619)

          总结:对于CheckedException,通过try、catch方式解决即可


(2)UnCheckedException

          也就是RuntimeException、Error等没法捕获的异常、错误

                1.问题引入

public class ThreadTest {  
    public static void main(String[] args) {  
    	MyTask task = new MyTask();  
        Thread thread = new Thread(task);  
          
        thread.start();  
    }  
} 

class MyTask implements Runnable {
	public void run() {
		int result = 3/0;
	}
}
               结果为:

Exception in thread "Thread-0" java.lang.ArithmeticException: / by zero
	at my.MyTask.run(ThreadTest.java:14)
	at java.lang.Thread.run(Thread.java:619)
             实际上也抛出了异常,但是无法对异常进行处理

                2.解决方案

                    1)需要单独处理的异常

                         自定义类实现UncaughtExceptionHandler接口,然后为线程设置

import java.lang.Thread.UncaughtExceptionHandler;

public class ThreadTest {  
    public static void main(String[] args) {  
    	MyTask task = new MyTask();  
        Thread thread = new Thread(task);  
        thread.setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());//为线程设置
        thread.start();  
    }  
} 

class MyTask implements Runnable {
	public void run() {
		int result = 3/0;
	}
}

class MyUncaughtExceptionHandler implements UncaughtExceptionHandler{

	public void uncaughtException(Thread t, Throwable e) {
		System.out.println("an uncaught exception occured!");
		System.out.println("thread state is :"+t.getState());
		System.out.println("thread name is :"+t.getName());
		System.out.println("error message is :"+e.getMessage());
		System.out.println("exception stack trace begin:");
		e.printStackTrace();
		System.out.println("exception stack trace end");
	}
}
                 结果为:

an uncaught exception occured!
thread state is :RUNNABLE
thread name is :Thread-0
error message is :/ by zero
exception stack trace begin:
java.lang.ArithmeticException: / by zero
	at my.MyTask.run(ThreadTest.java:16)
	at java.lang.Thread.run(Thread.java:619)
exception stack trace end
             可见可以在其中做异常处理

                    2 )处理方法基本相同的异常

                          定义ThreadFactory,使用统一的异常处理

import java.lang.Thread.UncaughtExceptionHandler;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

public class ThreadTest {  
    public static void main(String[] args) {  
    	ExecutorService executorService = Executors.newCachedThreadPool(new MyThreadFacotry());
    	executorService.execute(new MyTask());
    }  
} 

class MyTask implements Runnable {
	public void run() {
		int result = 3/0;
	}
}

class MyUncaughtExceptionHandler implements UncaughtExceptionHandler{

	public void uncaughtException(Thread t, Throwable e) {
		System.out.println("an uncaught exception occured!");
		System.out.println("thread state is :"+t.getState());
		System.out.println("thread name is :"+t.getName());
		System.out.println("error message is :"+e.getMessage());
		System.out.println("exception stack trace begin:");
		e.printStackTrace();
		System.out.println("exception stack trace end");
	}
}

class MyThreadFacotry implements ThreadFactory{

	public Thread newThread(Runnable r) {
		System.out.println("创建一个新的线程");
                Thread t = new Thread(r);
                t.setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
                return t;
	}
}
             结果为:

创建一个新的线程
an uncaught exception occured!
thread state is :RUNNABLE
thread name is :Thread-0
error message is :/ by zero
exception stack trace begin:
java.lang.ArithmeticException: / by zero
	at my.MyTask.run(ThreadTest.java:21)
	at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
	at java.lang.Thread.run(Thread.java:619)
exception stack trace end


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值