java中有两类异常:

已检查异常:这类异常编译器要求开发者必须在代码中通过throws去处理。

例如:IOException和ClassNotFoundException。

未检查异常:不必显式的在代码重处理。例如:NumberFormatException。

所有派生自Error和RuntimeException的类,都是未检查异常.其余的是已检查异常.

当一个已检查异常在线程对象的run()方法中抛出,我们就必须去捕捉并处理它,因为run()方法不接受throws条件。

而当一个未检查异常在run()方法中抛出,其默认行为是将异常信息输出到控制台并退出程序。

幸运的是,Java提供了在线程中捕捉和处理未检查异常的机制,以避免程序结束。

本例就来学习一下这一机制。

  1. Task.java
  1. package com.dylan.thread.ch1.c08.task;
  2. /**
  3. * Runnable class than throws and Exception
  4. *
  5. */
  6. public class Task implements Runnable {
  7. /**
  8. * Main method of the class
  9. */
  10. @Override
  11. public void run() {
  12. // The next instruction always throws and exception
  13. int numero=Integer.parseInt("TTT");
  14. }
  15. }
  1. ExceptionHandler.java
  1. package com.dylan.thread.ch1.c08.handler;
  2. import java.lang.Thread.UncaughtExceptionHandler;
  3. /**
  4. * Class that process the uncaught exceptions throwed in a Thread
  5. *
  6. */
  7. public class ExceptionHandler implements UncaughtExceptionHandler {
  8. /**
  9. * Main method of the class. It process the uncaught excpetions throwed
  10. * in a Thread
  11. * @param t The Thead than throws the Exception
  12. * @param e The Exception throwed
  13. */
  14. @Override
  15. public void uncaughtException(Thread t, Throwable e) {
  16. System.out.printf("An exception has been captured\n");
  17. System.out.printf("Thread: %s\n",t.getId());
  18. System.out.printf("Exception: %s: %s\n",e.getClass().getName(),e.getMessage());
  19. System.out.printf("Stack Trace: \n");
  20. e.printStackTrace(System.out);
  21. System.out.printf("Thread status: %s\n",t.getState());
  22. }
  23. }
  1. Main.java
  1. package com.dylan.thread.ch1.c08.core;
  2. import com.dylan.thread.ch1.c08.handler.ExceptionHandler;
  3. import com.dylan.thread.ch1.c08.task.Task;
  4. /**
  5. * Main class of the example. Initialize a Thread to process the uncaught
  6. * exceptions and starts a Task object that always throws an exception
  7. *
  8. */
  9. public class Main {
  10. /**
  11. * Main method of the example. Initialize a Thread to process the
  12. * uncaught exceptions and starts a Task object that always throws an
  13. * exception
  14. * @param args
  15. */
  16. public static void main(String[] args) {
  17. // Creates the Task
  18. Task task=new Task();
  19. // Creates the Thread
  20. Thread thread=new Thread(task);
  21. // Sets de uncaugh exceptio handler
  22. thread.setUncaughtExceptionHandler(new ExceptionHandler());
  23. // Starts the Thread
  24. thread.start();
  25. try {
  26. thread.join();
  27. } catch (InterruptedException e) {
  28. e.printStackTrace();
  29. }
  30. System.out.printf("Thread has finished\n");
  31. }
  32. }

运行结果:

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

Java并发编程实例--8.在线程中处理未检查异常的更多相关文章

  1. Java并发编程 | 从进程、线程到并发问题实例解决

    计划写几篇文章讲述下Java并发编程,帮助一些初学者成体系的理解并发编程并实际使用,而不只是碎片化的了解一些Synchronized.ReentrantLock等技术点.在讲述的过程中,也想融入一些相 ...

  2. Java并发编程:如何创建线程?

    Java并发编程:如何创建线程? 在前面一篇文章中已经讲述了在进程和线程的由来,今天就来讲一下在Java中如何创建线程,让线程去执行一个子任务.下面先讲述一下Java中的应用程序和进程相关的概念知识, ...

  3. 【转】Java并发编程:如何创建线程?

    一.Java中关于应用程序和进程相关的概念 在Java中,一个应用程序对应着一个JVM实例(也有地方称为JVM进程),一般来说名字默认是java.exe或者javaw.exe(windows下可以通过 ...

  4. [Java并发编程(二)] 线程池 FixedThreadPool、CachedThreadPool、ForkJoinPool?为后台任务选择合适的 Java executors

    [Java并发编程(二)] 线程池 FixedThreadPool.CachedThreadPool.ForkJoinPool?为后台任务选择合适的 Java executors ... 摘要 Jav ...

  5. [Java并发编程(一)] 线程池 FixedThreadPool vs CachedThreadPool ...

    [Java并发编程(一)] 线程池 FixedThreadPool vs CachedThreadPool ... 摘要 介绍 Java 并发包里的几个主要 ExecutorService . 正文 ...

  6. 2、Java并发编程:如何创建线程

    Java并发编程:如何创建线程? 在前面一篇文章中已经讲述了在进程和线程的由来,今天就来讲一下在Java中如何创建线程,让线程去执行一个子任务.下面先讲述一下Java中的应用程序和进程相关的概念知识, ...

  7. 原创】Java并发编程系列2:线程概念与基础操作

    [原创]Java并发编程系列2:线程概念与基础操作 伟大的理想只有经过忘我的斗争和牺牲才能胜利实现. 本篇为[Dali王的技术博客]Java并发编程系列第二篇,讲讲有关线程的那些事儿.主要内容是如下这 ...

  8. Java 并发编程——Executor框架和线程池原理

    Eexecutor作为灵活且强大的异步执行框架,其支持多种不同类型的任务执行策略,提供了一种标准的方法将任务的提交过程和执行过程解耦开发,基于生产者-消费者模式,其提交任务的线程相当于生产者,执行任务 ...

  9. Java 并发编程——Executor框架和线程池原理

    Java 并发编程系列文章 Java 并发基础——线程安全性 Java 并发编程——Callable+Future+FutureTask java 并发编程——Thread 源码重新学习 java并发 ...

  10. [转载] java并发编程:Lock(线程锁)

    作者:海子 原文链接: http://www.cnblogs.com/dolphin0520/p/3923167.html 出处:http://www.cnblogs.com/dolphin0520/ ...

随机推荐

  1. 使用Python+FFMPEG实现视频分割与合并

    前言 日常中偶尔会遇到需要简单剪辑处理视频的场景,以前我可能会拿出PR来剪辑一下,(别跟我说国产那些软件,剪辑完视频强制加上广告片头片尾恶心的一批),但是PR毕竟太重量级,剪个简单的视频都要花不少时间 ...

  2. [转帖]JVM随笔 --- 安全点(safe point)与 安全区域( safe region)

    https://zhuanlan.zhihu.com/p/461298916 11 人赞同了该文章 最近回顾 JVM safe point 与 safe region 又有一些新的感悟与收获,特别写篇 ...

  3. blackbox的简单学习-监控web服务是否正常以及证书过期时间

    blackbox的简单学习-监控web服务是否正常以及证书过期时间 下载blackbox https://github.com/prometheus/blackbox_exporter 可以在rele ...

  4. [转帖]InfluxDB 修改数据存储路径

    1.创建数据存储目录 mkdir -p /home/data/influxdb 说明:目录可以根据实际情况进行修改. 2.设置目录访问权限 sudo chown influxdb.influxdb / ...

  5. [转帖]oracle数据库中RMAN备份格式化format解释

    格式化解释: 使用格式串 更改格式命令: RMAN> configure channel device type disk format ' E:\app\Administrator\db_ba ...

  6. [转帖]Web技术(五):HTTP/2 是如何解决HTTP/1.1 性能瓶颈的?

    文章目录 一.HTTP/2 概览 二.HTTP/2 协议原理 2.1 Binary frame layer 2.1.1 DATA帧定义 2.1.2 HEADERS帧定义 2.2 Streams and ...

  7. [转帖]echo “新密码”|passwd --stdin 用户名

    https://www.cnblogs.com/rusking/p/6912809.html --stdin This option is used to indicate that passwd s ...

  8. [转帖]88. sys_kwr

    88. sys_kwr ¶ 88.1. 插件sys_kwr简介 ¶ 插件sys_kwr是KingbaseES 的一个扩展插件.主要功能是通过周期性自动记录性能统计相关的快照,分析出KingbaseES ...

  9. [转帖]lsblk命令详解

    https://www.cnblogs.com/ishmaelwanglin/p/11043918.html lsblk命令用来查看block设备的信息. 主要应用场景: 获取wwnid,获取块设备列 ...

  10. [转帖]Redis命令详解:Keys

    https://jackeyzhe.github.io/2018/09/22/Redis%E5%91%BD%E4%BB%A4%E8%AF%A6%E8%A7%A3%EF%BC%9AKeys/ 介绍完Re ...