Java并发编程实例--8.在线程中处理未检查异常
java中有两类异常:
已检查异常:这类异常编译器要求开发者必须在代码中通过throws去处理。
例如:IOException和ClassNotFoundException。
未检查异常:不必显式的在代码重处理。例如:NumberFormatException。
所有派生自Error和RuntimeException的类,都是未检查异常.其余的是已检查异常.当一个已检查异常在线程对象的run()方法中抛出,我们就必须去捕捉并处理它,因为run()方法不接受throws条件。
而当一个未检查异常在run()方法中抛出,其默认行为是将异常信息输出到控制台并退出程序。
幸运的是,Java提供了在线程中捕捉和处理未检查异常的机制,以避免程序结束。本例就来学习一下这一机制。
Task.java
package com.dylan.thread.ch1.c08.task;
/**
* Runnable class than throws and Exception
*
*/
public class Task implements Runnable {
/**
* Main method of the class
*/
@Override
public void run() {
// The next instruction always throws and exception
int numero=Integer.parseInt("TTT");
}
}
ExceptionHandler.java
package com.dylan.thread.ch1.c08.handler;
import java.lang.Thread.UncaughtExceptionHandler;
/**
* Class that process the uncaught exceptions throwed in a Thread
*
*/
public class ExceptionHandler implements UncaughtExceptionHandler {
/**
* Main method of the class. It process the uncaught excpetions throwed
* in a Thread
* @param t The Thead than throws the Exception
* @param e The Exception throwed
*/
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.printf("An exception has been captured\n");
System.out.printf("Thread: %s\n",t.getId());
System.out.printf("Exception: %s: %s\n",e.getClass().getName(),e.getMessage());
System.out.printf("Stack Trace: \n");
e.printStackTrace(System.out);
System.out.printf("Thread status: %s\n",t.getState());
}
}
Main.java
package com.dylan.thread.ch1.c08.core;
import com.dylan.thread.ch1.c08.handler.ExceptionHandler;
import com.dylan.thread.ch1.c08.task.Task;
/**
* Main class of the example. Initialize a Thread to process the uncaught
* exceptions and starts a Task object that always throws an exception
*
*/
public class Main {
/**
* Main method of the example. Initialize a Thread to process the
* uncaught exceptions and starts a Task object that always throws an
* exception
* @param args
*/
public static void main(String[] args) {
// Creates the Task
Task task=new Task();
// Creates the Thread
Thread thread=new Thread(task);
// Sets de uncaugh exceptio handler
thread.setUncaughtExceptionHandler(new ExceptionHandler());
// Starts the Thread
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.printf("Thread has finished\n");
}
}
运行结果:
An exception has been captured
Thread: 10
Exception: java.lang.NumberFormatException: For input string: "TTT"
Stack Trace:
java.lang.NumberFormatException: For input string: "TTT"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at com.dylan.thread.ch1.c08.task.Task.run(Task.java:16)
at java.lang.Thread.run(Thread.java:745)
Thread status: RUNNABLE
Thread has finished