• 线程中不可控异常处理


    在JAVA中有两种异常:

    • 非运行时异常(Checked Execption):这种异常必须在方法中声明throws语句指定,或者在方法体内捕获。例如IOException和ClassNotFoundException。
    • 运行时异常(unChecked exception):这种异常不必在方法中声明指定,也不需要在方法体捕获。例如NumberFormatException。

      因为run()方法不支持throws语句,所以当线程对象的run()方法抛出非运行异常时,我们必须捕获并且处理。在运行时异常从run()方法抛出时,默认行为是在控制台输出堆栈记录并退出程序。

    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
    ");
    		System.out.printf("Thread: %s
    ",t.getId());
    		System.out.printf("Exception: %s:%s
    ",e.getClass().getName(),e.getMessage());
    		System.out.printf("Stack Trace: 
    ");
    		e.printStackTrace(System.out);
    		System.out.printf("Thread status: %s
    ",t.getState());
    	}
    
    }
    
    /**
     * Runnable class than throws and Exception
     */
    public class Task implements Runnable {
    	@Override
    	public void run() {
    		// The next instruction always throws and exception
    		int numero=Integer.parseInt("TTT");
    	}
    }
    
    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) {
    		Task task=new Task();
    		Thread thread=new Thread(task);
    		thread.setUncaughtExceptionHandler(new ExceptionHandler());
    		thread.start();
    		try {
    			thread.join();
    		} catch (InterruptedException e) {
    			e.printStackTrace();
    		}
    		System.out.printf("Thread has finished
    ");
    	}
    }
    

       工作原理:当一个线程抛出了异常并且没有捕获异常时,JVM检查这个线程是否设置了未捕获异常处理器。如果找到,JVM将调用这个线程对象的这个方法,并将线程对象和异常作为参数传入。

      当线程抛出一个未捕获异常时,JVM将为异常寻找一下三种可能的处理:

      首先,查找对象的未捕获异常处理器,如果找不着,JVM继续查找线程对象所在线程组的未捕获异常处理器。如果还找不到,JVM继续查找默认的未捕获异常处理器。如果没有一个处理器存在,JVM将堆栈异常记录打印到控制台,并退出程序。

  • 相关阅读:
    Codeforces 934 B.A Prosperous Lot
    Codeforces 934 A.Compatible Pair
    UVA 12898
    Codeforces Round #376 (Div. 2) C. Socks bfs
    Codeforces Round #377 (Div. 2) C. Sanatorium 水题
    Codeforces Round #377 (Div. 2) D. Exams 二分
    Codeforces Beta Round #91 (Div. 1 Only) E. Lucky Array 分块
    hdu 5154 Harry and Magical Computer 拓扑排序
    Codeforces Round #272 (Div. 2) C. Dreamoon and Sums 数学
    Codeforces Round #288 (Div. 2) C. Anya and Ghosts 模拟
  • 原文地址:https://www.cnblogs.com/wxgblogs/p/5500654.html
Copyright © 2020-2023  润新知