通过对异常链遍历找到原始异常

Java学习day047 捕获异常(捕获异常、捕获多个异常、再次抛出异常与异常链) 使用的教材是java核心技术卷1,我将跟着这本书的章节同时配合视频资源来进行学习基础java知识。 day047 捕获异常(捕获异常、捕获多个异常、再次抛出异常与异常链) ... 阅读详情
异常链:常常会在捕获一个异常后抛出另外一个异常,并且希望把异常原始信息保存下来,这被称为异常链。
如果调用一个方法需要对该方法进行异常处理,而想要获得产生异常的根源,可以参考下面的例子。
//自定义异常ExceptionA
public class ExceptionA extends Exception{

    public ExceptionA(String e) {
        super(e);
    }
    public ExceptionA() {
    }
    public ExceptionA(String e,Throwable cause)
    {
        super(e,cause);
    }
    public  ExceptionA(Throwable cause) {
        super(cause);
    }
}
//自定义异常ExceptionB
public class ExceptionB extends Exception{

    public ExceptionB(String e) {
        super(e);
    }
    public ExceptionB() {
        // TODO Auto-generated constructor stub
    }
    public ExceptionB(String e,Throwable cause)
    {
        super(e,cause);
    }
    public  ExceptionB(Throwable cause) {
        super(cause);
    }

}
public class Test {

    public static void main(String[] args) {
        try {
            testa();
        } catch (ExceptionA e) {
        //对异常信息进行遍历,输出异常信息中的原始异常,直到找到最终的原始异常
            Throwable throwable = e;
            while(throwable != null)
            {
                System.out.println(throwable);
                throwable = throwable.getCause();
            }
        }

    }
    public static void testa() throws ExceptionA
    {
        try {
            testb();
        } catch (ExceptionB e) {

            throw new ExceptionA("产生了异常A",e);
        }
    }
    public static void testb() throws ExceptionB
    {
        try {
            throw new Exception("产生了异常");
        } catch (Exception e) {

            throw new ExceptionB("产生了异常B",e);
        }
    }

}

最后的输出结果:
这里写图片描述

非常简单的一个例子,程序中的重点是getCause方法的使用,getCause的作用是返回异常对象中的原始异常,通过getCause方法获得原始异常,再通过原始异常调用getCause方法获得更深一层的原始异常,一直循环直到获得最原始的异常

深入Windows SEH:从FS:[0]异常链到x64表驱动与安全防御 结构化异常处理(SEH)是Windows平台上C/C++程序员必须掌握的核心机制,它决定了程序在遇到除零、非法内存访问等错误时如何优雅地接管流程。理解SEH的起点,往往从线程环境块(TEB)开头的FS:[0]指针开始,它指向一条动态挂接在栈上的异常处理链。当异常发生时,系统沿链分发,编译器在背后将__try/__except翻译为特定的栈帧注册与scopetable查询。然而,x64架构摒弃了易受缓冲区溢出破坏的链式结构,改用.pdata与UNWIND_INFO组成的只读表驱动方案,大幅提升了安全性。在实际 阅读详情

相关推荐

信创改造实战:SpringBoot项目迁移到宝兰德BES 9.5.5的完整避坑指南(附依赖与web.xml配置)

本文详细介绍了将SpringBoot项目迁移到宝兰德BES 9.5.5的完整流程,包括依赖改造、web.xml配置降级等关键步骤。通过实战案例和避坑指南,帮助开发者高效完成国产中间件适配,确保项目平稳运行。特别针对Tomcat依赖排除和BES适配器选择提供了专业建议。

weixin_30689307的博客 742

Java中获取Exception的详细信息

当代码出现异常时通常都需要将异常信息写入到日志中,异常信息越详细越有利于问题的排查。而通过的Exception.getMessage()方法只能获得异常的名称而不能获取哪里出现的异常,对于排错意义不大。 //1、 public String getTrace(Throwable t) { StringWriter stringWriter= new StringWriter(); ...

fall_hat的博客 7277

【Qt-4】QT基于qhttp-server搭建http服务器

QT搭建http服务器

WXG1011的博客 5714

如何实现二次抛异常时保存第一次异常的详细信息?

我用反射来尝试调用一个可能会引发异常的方法,我如何将这个异常信息传递给调用者,而不需要通过反射包装器包装它。

寒冰屋的专栏 378

国产操作系统应用迁移与适配

了解国产操作系统的背景及意义

2301_77609559的博客 2680

Oracle 从入门到精通系列(入门篇)1.1-Oracle 数据库发展史

Oracle 从入门到精通系列(入门篇)1.1-Oracle 数据库发展史

LuciferLiu_DBA 2191

通过Exception获取其中的信息

private static String getCrashMessage(Exception ex) {         Writer writer = new StringWriter();         PrintWriter printWriter = new PrintWriter(writer);         ex.printStackTrace(printWriter);

qq_24179679的博客 1255

【DRAM存储器六十八】DDR5介绍--DQS Interval Oscillator—动态时序校准利器

DDR5内存采用DQS间隔振荡器(DQSIntervalOscillator)技术应对高速数据传输中的时序漂移问题。该技术通过测量DQS信号在可编程时间窗口内的振荡次数(16位计数值),动态监测温度/电压变化导致的DQS-DQ延迟偏移。控制器通过MPC命令启停振荡器,读取MR46/MR47寄存器获取计数值,并与基准值对比来调整DQS相位,确保数据采样窗口始终处于最佳位置。该机制使DDR5在8400MT/s高速率下仍能保持数据可靠性,有效补偿±0.48tCK的时序偏移。

highman110的博客 153

SpringBoot 中使用 RestTemplate 自定义 异常处理,捕获最原始的错误信息

一些 API 的报错信息通过 Response 的 body返回。 使用 HttpClient 能正常获取到 StatusCode 和 body 中的错误提示。然而使用 RestTemplate ,会直接抛出下面的异常。 如果想获取原始的信息并进一步处理会比较麻烦。 类似下面这种404、403响应码直接抛出异常并不是我们想要的 org.springframework.web.clie...

phubing 8722

Python 爬虫高级实战:HTTPS 证书忽略与代理抓包配置

本文深入解析了HTTPS加密与SSL证书校验机制在爬虫开发中的核心问题及解决方案。文章首先剖析了HTTPS协议架构和证书校验流程,指出爬虫开发中常见的证书异常场景及其负面影响。随后详细介绍了Python主流请求库(requests、httpx、aiohttp)的证书忽略配置方法,包括同步/异步模式下的实现方案。针对代理环境,文章系统比较了HTTP、HTTPS、SOCKS5等代理类型的特性差异,并提供了完整的代理配置示例。特别对中间人抓包场景,阐述了Mitmproxy的工作原理和配置要点。最后提出了工程级爬虫

2503_91057718的博客 86

硬件工程师笔记——运算放大电路Multisim电路仿真实验汇总

本文系统介绍了运算放大电路的基础知识及其应用。主要内容包括:1)运算放大器的基本结构、理想特性及分析方法(虚短、虚断、叠加定理);2)比例运算电路(同向、反向、差分)的工作原理与仿真分析;3)求和运算、加减运算电路的实现方法;4)积分、微分、指数和对数运算电路的基本原理;5)过零电压比较器的功能特点。通过理论分析和仿真实验,详细阐述了各类运算放大电路的输入输出特性、相位关系和增益计算,为硬件工程师提供了实用的电路设计参考。

XU157303764的博客 2482

异常链

百目鬼(Java学生) 541

【技术科普】破解政务跨系统数据壁垒!亘川一网统管平台多源数据同步技术解析

本文解析亘川一网统管平台多源数据同步技术,针对政务跨系统数据壁垒难题,介绍组件的数据采集、校验、审计留痕等核心能力,结合营商环境项目落地案例,对比传统开发模式差异,讲解开源组件的实践价值,为政务项目开发者提供落地参考。

weixin_67440240的博客 635

异常转译与异常链

  1、异常转译的原理 所谓的异常转译就是将一种异常转换另一种新的异常,也许这种新的异常更能准确表达程序发生异常。 在Java中有个概念就是异常原因,异常原因导致当前抛出异常的那个异常对象,几乎所有带异常原因的异常构造方法都使用Throwable类型做参数,这 也就为异常的转译提供了直接的支持,因为任何形式的异常和错误都是Throwable的子类。比如将SQLExce

dichyzhu的专栏 2792

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

异常:异常链

/* *  2018年3月28日10:43:45 *  代码目的: *      演示异常链的使用 *      常常会想要在捕获一个异常好抛出另外一个异常, *      并且希望把原始异常的消息保存下来,这被称为异常链 *       *      Throwable的子类在构造器中都可以加收一个cause因由对象作为参数, *      这个cause就表示原始异常,这样通过把原始异常传...

不当初 811

深度学习工具包 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")

Win32 SEH异常深度探索_2 异常链表遍历

With this simplest of scenarios behind us, lets goback and fill in some of the blanks. While this exception callback is great,its not a perfect solution. In an application of any size, it would

hongjiqin的专栏 1654

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

Python 中 raise 与 assert 的正确用法:从异常链到边界管理

异常处理是 Python 工程中保障代码健壮性的关键一环,而 raise 与 assert 又常被开发者混淆。raise 是主动抛出异常,用于业务错误与外部依赖失败的信号传递;assert 则是基于 __debug__ 开关的断言机制,适合守护算法不变量与调试期检查。理解二者原理差异,能避免线上开启 -O 后断言失效、参数校验形同虚设等隐患。围绕异常链、traceback 定位、接口参数校验等实战场景,合理编排错误处理逻辑,才能让程序在复杂链路下保持可控。本文通过对比机制、剖析踩坑案例,梳理 raise 与

weixin_34406086的博客 303

【笔记73】抛出与抽象相对应的异常

异常链顾名思义就是将异常发生的原因一个传一个串起来,即把底层的异常信息传给上层,这样逐层抛出。Java API文档中给出了一个简单的模型: try { lowLevelOp(); } catch (LowLevelException le) { throw (HighLevelException) new HighLevelException().initCau...

u013773608的博客 1931

MiGPT 完整指南:10 分钟把小爱音箱接入 ChatGPT

你问小爱一个问题,她只会回一句 canned 笑话;你想要连续对话,却得每句话都喊一次唤醒词。这篇指南用 MiGPT 把你的小爱音箱接入 ChatGPT,10 分钟跑通,适合有小爱音箱和米家账号的新手。 > **注意**:MiGPT 目前处于停止维护状态,不再提供更新与支持,下文已有功能可正常使用,请以官方仓库说明为准。 可以把 MiGPT 理解成装在音箱上的"翻译加配音员":它监听你跟小爱的

gitblog_01023的博客 252

2.内核异常处理流程

用户层异常与内核层异常 异常可以发生在用户空间,也可以发生在内核空间。 无论是CPU异常还是模拟异常,是用户层异常还是内核异常,都要通过 KiDispatchException函数进行分发,这个函数比较复杂。 VOID KiDispatchException ( ExceptionRecord, ExceptionFrame, TrapFrame, PreviousMode, First...

My classmates 1584

Java的java.lang.StackWalker调用栈截取与异常链在错误报告中的增强

传统的StackTraceElement在性能和分析粒度上存在局限,而Java 9引入的java.lang.StackWalker为开发者提供了更高效、灵活的调用栈遍历能力。结合异常链的增强处理,这一机制显著提升了错误报告的可读性和调试效率,尤其在微服务或高并发场景下,成为优化系统健壮性的关键工具。例如,在多层RPC调用中,能快速定位跨服务的原始错误点,而传统方式需手动拼接多个异常的栈信息,易遗漏关键上下文。相比静态日志输出,这种动态绑定避免了硬编码,且能适配反射或代理场景,确保日志的准确性。

nalfbb_270的博客 323

用户层和内核层异常的处理流程

文章目录内核层异常的处理流程用户层异常和内核层异常KiDispatchException函数详解RtlDispatchException函数的执行流程用户层异常的处理流程用户异常的处理流程 内核层异常的处理流程 之前已经了解过异常处理机制的执行流程:异常记录 异常分发 异常的处理。这次我们学习一下内核异常的分发与处理。 用户层异常和内核层异常 异常可以发生在用户空间,也可以发生在内核空间。无论是C...

鬼手的博客 2621
上一篇: 一个关于成员变量的多态问题
下一篇: java不支持泛型数组
ComTNT
博客等级 码龄10年 5粉丝 12原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值