利用UncaughtExceptionHandler全局处理线程异常

处理线程未捕获的异常UncaughtExceptionHandler 为什么需要UncaughtExceptionHandler? 1.主线程可以轻松发现异常,子线程却不行(比如子线程抛出了RuntimeException异常,而主线程start子线程后后续还有很多逻辑,子线程的异常可能夹杂在日志里无法轻松发现)。 2.子线程异常无法用传统方法捕获(比如在主方法里try/catch不能捕获到子线程里面的异常,他只能捕获主线程的异常)。 处理多线程子线程的异常有两种方式: 第一种是手动在每个run方法里进行try/catch,不推荐这种方式,写起来繁琐。 第二种是利用Uncau 阅读详情

线程的未捕获异常UncaughtException应该如何处理?

为什么需要UncaughtExceptionHandler?

  • 主线程可以轻松发现异常,子线程却不行;
  • 子线程异常,无法用传统方法进行捕获;

代码演示:

/** 单线程,抛出,处理,有异常堆栈
    多线程,子线程发送异常,会有什么不同
 * */
public class ExceptionInChildThread implements Runnable{

    @Override
    public void run() {
        throw  new RuntimeException();
    }

    public static void main(String[] args) {
        new Thread(new ExceptionInChildThread()).start();
        for(int i = 0; i < 1000; i++){
            System.out.println(i);
        }
    }
}

输出:

 

1.不加try catch 抛出4个异常,都带线程名字;

2.加了try catch,期望捕获到第一个线程的异常,线程234不应该运行,希望看到打印出Caught Exception;

3.执行时发现,根本没有Caught Exception,线程234依然运行,并且抛出异常 说明线程的异常不能用传统方法捕获。

代码演示:

public class CantCatchDirectly implements Runnable{

    @Override
    public void run() {
        throw new RuntimeException();
    }

    public static void main(String[] args) throws InterruptedException {
        try{
            new Thread(new CantCatchDirectly(),"MyThread-1").start();
            Thread.sleep(300);
            new Thread(new CantCatchDirectly(),"MyThread-2").start();
            Thread.sleep(300);
            new Thread(new CantCatchDirectly(),"MyThread-3").start();
            Thread.sleep(300);
            new Thread(new CantCatchDirectly(),"MyThread-4").start();
        }catch (RuntimeException e){
            System.out.println("Caught Exception.");
        }
    }
}

输出结果;

此处try catch是针对主线程的,没有办法捕捉的子线程的异常,所以这里传统方法失效。

 

推荐解决方法:利用UncaughtExceptionHandler

  • UncaughtExceptionHandler接口
  • void uncaughtException(Thread t, Throwable e);

这里给程序设置统一的异常捕获:

分别新建两个类,UseOwnUncaughtExceptionHandler.java ,MyUncaughtExceptionHandler.java。

代码如下:

import java.util.logging.Level;
import java.util.logging.Logger;

/** 自行设置的 MyUncaughtExceptionHandler */
public class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler{

    private String name;

    public MyUncaughtExceptionHandler(String name) {
        this.name = name;
    }

    /** 传入参数:
      Thread t:产生异常的线程;
     Throwable e:具体的异常信息
     * */
    @Override
    public void uncaughtException(Thread t, Throwable e) {
       Logger logger = Logger.getAnonymousLogger();
       logger.log(Level.WARNING," 线程异常,已终止 "+t.getName(),e);
        System.out.println(name + "捕获了异常" + t.getName() + "异常" + e);
    }
}
/** 使用刚才自己写的UncaughtExceptionHandler */
public class UseOwnUncaughtExceptionHandler implements Runnable{

    @Override
    public void run() {
        throw new RuntimeException();
    }

    public static void main(String[] args) throws InterruptedException {
        Thread.setDefaultUncaughtExceptionHandler(new MyUncaughtExceptionHandler("异常捕获器1"));
            new Thread(new UseOwnUncaughtExceptionHandler(),"MyThread-1").start();
            Thread.sleep(300);
            new Thread(new UseOwnUncaughtExceptionHandler(),"MyThread-2").start();
            Thread.sleep(300);
            new Thread(new UseOwnUncaughtExceptionHandler(),"MyThread-3").start();
            Thread.sleep(300);
            new Thread(new UseOwnUncaughtExceptionHandler(),"MyThread-4").start();
    }
}

运行UseOwnUncaughtExceptionHandler.java:

 

run()方法本身方法声明的时候,没有声明抛出异常,所以在方法层面,我们只能自己去做try catch处理。

 

Java 捕获并处理线程异常:Thread线程异常捕获、ThreadPoolExecutor线程池异常捕获 Thread.UncaughtExceptionHandler捕获线程异常 ThreadPoolExecutor#afterExecute方法捕获线程池异常 以及两者实现的原理 阅读详情

相关推荐

学习使用turtlebot2——ROS上安装turtlebot2

安装环境:    安装Ubuntu 14.04版本和ROS Indigo    参考:http://wiki.ros.org/turtlebot/Tutorials安装步骤    有两种安装方法,一种直接的安装命令,另外一种源码编译安装,区别在于:直接安装命令是安装在电脑默认路径/opt/ros/indigo/share里面不便于更改代码,因为默认路径下文件一般有访问权限,无法直接更改,需要使用s...

weixin_42670641的博客 2531

如何处理UncaughtException异常

如何处理UncaughtException异常为什么要处理UncaughtException异常怎么处理UncaughtException异常线程很容易被发现,子线程中的异常不易被发现。子线程抛出的异常无法使用传统方法捕获。直接捕获异常可以提高代码的健壮性。使用UncaughtExceptionHandler处理未捕获的异常 为什么要处理UncaughtException异常 在一个项目中,会有很多UncaughtException异常。如果这些异常没有处理,就有可能把异常信息返回给前端,黑客看到这些异常的

papinick的博客 1万+

虚幻UE 增强输入-触发器

输入触发器(UInputTrigger): 使用经过修饰器修改的输入值,或者使用其他输入动作的输出值,来确定是否激活输入动作。

UE成长之路,欢迎大家的关注! 5464

Java线程异常UncaughtExceptionHandler

捕获线程的执行异常 在线程的run方法中,如果有受检异常必须进行捕获处理,如果想要 获 得 run() 方 法 中 出 现 的 运 行 时 异 常 信 息 , 可 以 通 过 回 调 UncaughtExceptionHandler 接口获得哪个线程出现了运行时异常.在 Thread 类中有关处理运行异常的方法有: getDefaultUncaughtExceptionHandler() 获 得 全 局 的 ( 默 认 的)UncaughtExceptionHandler getUncaughtExcept

weixin_43939924的博客 1255

华为2288H-V5服务器做raid的详细步骤

操作步骤 服务器启动界面 按del键进入设置输入密码,2288H-v5默认密码是Admin@9000 移动光标选择device manager 驱动管理选择configurationutility 配置管理 选择main menu 主菜单 选择第一个 configuration management 配置管理 选择create virtual driver 创建虚拟驱动选择select RAID level 选择RAID等级选择level-5 选择select drivers 选择驱......

weixin_46041124的博客 1万+

Go语言集成Ollama本地大模型:gollama库实战指南

在当今的AI应用开发中,大型语言模型(LLM)的集成已成为关键技术。其核心原理是通过API调用,将自然语言处理能力嵌入到各类应用中。从技术价值看,本地化部署的LLM解决了数据隐私、网络延迟和持续成本三大痛点,尤其适合处理敏感数据或对实时性要求高的场景。在工程实践中,开发者常使用专门的客户端库来简化与模型服务的交互,例如通过封装REST API、提供类型安全接口和流式处理支持,从而提升开发效率和代码健壮性。具体到Go语言生态,结合Ollama这一流行的本地大模型运行工具,可以实现完全离线、低延迟的AI功能集成

weixin_28728443的博客 605

Crash: 处理UncaughtExcption,捕获未处理异常信息,界面友好提示用户

Crash: 处理UncaughtExcption,友好提示用户,捕获错误信息相信大家在APP使用过程都遇到过,应用程序异常崩溃,屏幕一黑闪退,这种情况称之为Crash。出现的原因是由于程序运行过程中产生了未知异常UncaughtException,当程序发生Crash时,系统会杀死程序,出现闪退,这种情况的用户体验不好,而且开发人员也不能知道用户发生了何种异常。 那么问题来了,发生Crash时我

萧萧北keno的专栏 2325

STM32cubeMX配置FreeRTOS软件定时器

文章目录前言1.软件定时器概述一.软件定时器特性二、使用cubeMX生成软件定时器总结 前言 本文主要带大家了解什么是软件定时器,并且带大家使用cubeMX配置软件定时器。 1.软件定时器概述 一.软件定时器特性 软件定时器就是一个闹钟当时间到了就执行相对应的任务或者代码。软件定时器是基于系统滴答中断的。在FreeRTOS中我们可以设置无数个软件定时器。 指定时间:启动定时器和运行回调函数,两者的间隔被称为定时器的周期 (period)。 指定类型定时器有两种类型: 1.一次性 这类定时器启动后,它的回调函

m0_49476241的博客 6949

线程的未捕获异常UncaughtException应该如何处理?

可以使用UncaughtExceptionHandler,有以下的原因: 首先应该注意:try/catch只能捕获对应线程内的异常,不同的线程组合在一个用try/catch进行包起来不能进行捕获 主线程可以轻松发现异常,而子线程不行 子线程的异常不会影响到主线程的执行,即使子线程有异常抛出,并且打印了异常信息,主线程依然能够正常运行 子线程异常无法用传统方法进行捕获 ...

weibozhouchao的博客 2986

VS2019编译使用log4cplus 1.2.0

logger.properties 文件。第三步,创建项目来测试,配置库。第二步,使用VS2019编译。

h a 6 6 6 c k 为 你解决复杂难题! 527

基于YOLOv8的植物生长阶段识别系统设计与实现

本文详细介绍了一个基于YOLOv8深度学习模型的植物生长阶段识别系统,包含完整的数据集构建、模型训练、评估以及基于PyQt5的用户界面开发过程。系统能够自动识别植物在不同生长阶段(如发芽期、生长期、开花期、结果期等)的形态特征,为精准农业和智能种植提供技术支持。文章提供了完整的代码实现,并讨论了模型优化策略和实际应用场景。关键词:植物生长阶段识别、YOLOv8、目标检测、PyQt5、深度学习。

YOLO 465

第九章、核心7:线程异常处理(全局异常处理UncaughtExceptionHandler)

线程的未捕获异常UncaughtException应该如何处理? 1、为什么需要UncaughtExceptionHandler? 主线程可以轻松发现异常,子线程却不行 子线程异常无法用传统方法(try-catch)捕获(类似main方法中执行thread.start,抛出异常是在子线程的run中,而try-catch的是主线程main,所以捕获不到) 不能直接捕获会导致一些后果(无法捕获到异常,做相应的重试操作逻辑) 2、两种解决方案 方案一(不推荐):手动在每个run方法里进行try catch

Coder 678

FPGA 学习笔记:解决FPGA程序固化重新上电程序不运行的问题

FPGA 学习笔记:解决FPGA程序固化重新上电程序不运行的问题

坚韧与专注 1万+

Java多线程--全局异常处理--方法/实例

原文网址: 简介 说明 本文用示例介绍如何处理Java多线程中的异常。 在Java中,线程中的异常是不能抛出到调用该线程的外部方法中捕获的。 为什么不能抛出异常到外部线程捕获? 因为线程是独立执行的代码片断,线程的问题应该由线程自己来解决,而不要委托到外部。基于这样的设计理念,在Java中,线程方法的异常都应该在线程代码边界之内(run方法内)进行try catch并处理掉。换句话说,我们不能捕获从线程中逃逸的异常。 JDK如何控制线程异常不会跑...

IT利刃出鞘的博客 1723

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

多线程的未捕获异常类 UncaughtExceptionHandler 的使用

*** 自定义 UncaughtExceptionHandler*/@Overridelogger.log(Level.WARNING,"线程异常:"+t.getName(),e);System.out.println(name+"我捕获了异常"+t.getName()+"异常名字:"+e);

Qynwang的博客 2180

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

线程未捕获异常处理器Thread.UncaughtExceptionHandler

public class Test1 { /** * 线程未捕获异常处理器接口 Thread.UncaughtExceptionHandler * 此接口会在线程由于未捕获异常而突然终止时被调用 */ public static class CustomUncaughtExceptionHandler implements Thread.Uncaug...

CodingSoldier的博客 901

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

多线程核心7:处理未捕获的异常

使用UncaughtExceptionHandler的原因 主线程可以轻松发现异常,子线程不能 子线程的异常无法用传统方式捕获 在捕获到异常时也能进行处理,提高健壮性 全局异常处理使用方式 实现Thread.UncaughtExceptionHandler接口 public class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler { private String name; public

那股哇的博客 213

全局异常处理UncaughtExceptionHandler

android 程序错误处理全局处理 java线程unchecked 异常的处理UncaughtExceptionHandler

DevXP的专栏 700

Java并发编程之线程异常

多线程异常第一种处理方式:局部处理 在多线程编程中,如果主线程出现异常,我们可以使用try/catch等方式轻松的处理异常; 如果子线程出现异常,则需要在每个子线程中可能发生异常的地方用try/catch进行处理,代码如下: public class CommonThread implements Runnable { @Override public void run() {...

qq_36986015的博客 221

Java线程学习记录(九)——线程异常处理

线程的未捕获异常UncaughtException应该如何处理 为什么需要UncaughExceptionHandler 主线程可以轻松发现异常,子线程却不行 public class ExceptionInChildThread implements Runnable { public static void main(String[] args) { new Thread(new ExceptionInChildThread()).start(); for (i

Csea的博客 542

Java 线程异常处理

子线程中发生了异常,,而不会记录任何日志。所以,如果什么都不做的话,是会出现子线程任务既没执行成功,也没有任何日志提示的“诡异”现象的。

m0_74295055的博客 603

线程异常

此文章为微信公众号“我们都是小青蛙”学习笔记。 多个线程中的任务是并发执行的,一个线程中抛出的异常是不能被别的线程catch并处理的,比如main线程中的异常最多被抛到main方法中,其他线程中的异常最多能被抛到run方法,再往上抛就是传说中的虚拟机了。所以如果我们没有处理某个线程中抛出的异常,那这个线程只能死掉。 而Thread类给我们提供了一个所谓的异常处理器的接口 public class Thread implements Runnable { // ... 为节省篇幅,省略其他字段和方法

qq_30864125的博客 294

Android自定义Thread.UncaughtExceptionHandler异常线程捕获

1.Thread.UncaughtExceptionHandler类 背景: 未捕获异常大多发生在在多线程环境中,子线程抛出的异常是不能用主线程中 try….catch 捕获。可以给线程设置 UncaughtExceptionHandler ,当出现异常时会回调 UncaughtExceptionHandler 中的uncaughtException(Thread t, Throwable e) 方法 设置可以为某个线程单独设 thread.setUncaughtExceptionHandler(new M

脉冲星飞行记录 707

UncaughtExceptionHandler实例

UncaughtExceptionHandler实例

weixin_45428910的博客 385

【多线程】线程异常知多少?

1.常见问题 1.1 Java异常体系图 1.2 实际工作中,如何全局处理异常?为什么要全局处理?不处理行不行? 1.3 run方法是否可以抛出异常?如果抛出异常,线程的状态会怎么样? run()方法不可以向上抛出异常,只可以自己捕获,抛出异常后,线程停止运行,进入终止状态。 2. 线程的未捕获异常UncaughtException应该如何处理? 2.1 为什么需要UncaughtExceptionHandler? 主线程可以轻松发现异常,子线程却不行 /** * 描述:单线程,抛出处理,有异常堆

Dreamlate_Spider的博客 991

5.线程异常

程序执行结果如下所示,当Thread1抛出异常时,应当进入catch分支,并终止程序运行。但实际上没有,程序继续运行,4个子线程分别抛出异常,这说明使用try catch没有捕获到子线程异常。2.UncaughtExceptionHandler源码分析。程序执行结果如下所示,4个子线程抛出的异常都被捕获。1.不能用传统方法捕获线程异常。

Steven的博客 248
上一篇: Java内存模型原理小结
下一篇: Tomcat小记
专业逮虾户
博客等级 码龄7年 1粉丝 10原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值