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

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. [转帖]使用 TiUP 升级 TiDB

    本文档适用于以下升级路径: 使用 TiUP 从 TiDB 4.0 版本升级至 TiDB 7.1. 使用 TiUP 从 TiDB 5.0-5.4 版本升级至 TiDB 7.1. 使用 TiUP 从 Ti ...

  2. [转帖]InnoDB Page结构详解

    1导读 本文花了比较多的时间梳理了InnoDB page的结构以及对应的分裂测试,其中测试部分大部分是参考了叶老师在<InnoDB表聚集索引层什么时候发生变化>一文中使用的方法,其次,本文 ...

  3. [转帖]优化命令之iotop命令

    文章目录 引言 一.iotop简介 1.iotop安装 2.iotop语法 3.iotop参数 二.I/O的常用快捷键 三.交互模式 四.iotop示例 1.只显示正在产生I/O的进程 2.显示指定P ...

  4. [转帖]一行Python代码实现同一局域网内的文件共享

    在不同的设备之间传输文件除了数据线,网盘传输外是否还有其他优雅的方法?我们可以使用一行Python代码使局域网内的所有设备都可以访问并下载文件夹内的文件. 要求: 电脑中安装配置好python 访问的 ...

  5. 飞腾2000+银河麒麟v10安装redis的注意事项

    先说一下结论 无法复用ubuntu上面编译的二进制文件 无法直接使用docker官网下面的arm64的镜像运行 无法直接使用redis6.0.10最新版本编译运行 可以使用redis5.0.4 进行编 ...

  6. vue中sync的使用原来这么简单

    sync的使用场景 有些时候子组件需要修改父组件传递过来的prop, 要去改变父组件的状态的时候就需要使用aync 看见这里有些同学可能会问?? 不是说不可以修改父组件传递到子组件的值吗? 为啥要修改 ...

  7. gRPC基本教程

    原文在这里. 本教程为Go程序员提供了使用gRPC的基本介绍. 通过跟随本示例,你将学会如何: 在.proto文件中定义一个服务. 使用协议缓冲编译器生成服务器和客户端代码. 使用Go gRPC AP ...

  8. Prompt learning 教学[最终篇]:Chatgpt使用场景推荐、优秀学习资料推荐、AI工具推荐

    Prompt learning 教学[最终篇]:Chatgpt使用场景推荐.优秀学习资料推荐.AI工具推荐 1.chatgpt使用场景推荐 各位应该在各种平台看到不少可以尝试使用的场景,我这里仅收录: ...

  9. Jupyter Notebook 下 import 第三方库,显示 no module xxx 【本质是环境没有切换过来】

    1.最简单情况下 切换环境即可 首先激活环境: ​ activate env  # 激活你的环境名称 jupyter notebook ​ 之后去运行代码即可,如果还不行请看下面: 2.遇到Jupyt ...

  10. 5.4 Windows驱动开发:内核通过PEB取进程参数

    PEB结构(Process Envirorment Block Structure)其中文名是进程环境块信息,进程环境块内部包含了进程运行的详细参数信息,每一个进程在运行后都会存在一个特有的PEB结构 ...