浅析Java语言中两种异常使用的差别

详解Java中Checked Exception与Runtime Exception 的区别 主要介绍了详解Java中Checked Exception与Runtime Exception 的区别的相关资料,这里提供实例帮助大家学习理解这部分内容,需要的朋友可以参考下 立即下载
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script> 浅析Java语言中两种异常使用的差别 阅读次数1065 出处 作者:Sabine 来源:赛迪论坛 -------------------------------------------------------------------------------- Java提供了两类主要的异常:runtime exception和checked exception。所有的checked exception是从java.lang.Exception类衍生出来的,而runtime exception则是从java.lang.RuntimeException或java.lang.Error类衍生出来的。 它们的不同之处表现在两方面:机制上和逻辑上。 一、机制上 它们在机制上的不同表现在两点:1.如何定义方法;2. 如何处理抛出的异常。请看下面CheckedException的定义: public class CheckedException extends Exception {  public CheckedException() {}  public CheckedException( String message )  {   super( message );  } } 以及一个使用exception的例子: public class ExceptionalClass {  public void method1()   throws CheckedException   {    // ... throw new CheckedException( "...出错了" );   }  public void method2( String arg )   {    if( arg == null )    {     throw new NullPointerException( "method2的参数arg是null!" );    }   }  public void method3() throws CheckedException   {    method1();   } } 你可能已经注意到了,两个方法method1()和method2()都会抛出exception,可是只有method1()做了声明。另外,method3()本身并不会抛出exception,可是它却声明会抛出CheckedException。在向你解释之前,让我们先来看看这个类的main()方法: public static void main( String[] args ) {  ExceptionalClass example = new ExceptionalClass();  try  {   example.method1();   example.method3();  }  catch( CheckedException ex ) { } example.method2( null ); } 在main()方法中,如果要调用method1(),你必须把这个调用放在try/catch程序块当中,因为它会抛出Checked exception。 相比之下,当你调用method2()时,则不需要把它放在try/catch程序块当中,因为它会抛出的exception不是checked exception,而是runtime exception。会抛出runtime exception的方法在定义时不必声明它会抛出exception。 现在,让我们再来看看method3()。它调用了method1()却没有把这个调用放在try/catch程序块当中。它是通过声明它会抛出method1()会抛出的exception来避免这样做的。它没有捕获这个exception,而是把它传递下去。实际上main()方法也可以这样做,通过声明它会抛出Checked exception来避免使用try/catch程序块(当然我们反对这种做法)。 小结一下: * Runtime exceptions: 在定义方法时不需要声明会抛出runtime exception; 在调用这个方法时不需要捕获这个runtime exception; runtime exception是从java.lang.RuntimeException或java.lang.Error类衍生出来的。 * Checked exceptions: 定义方法时必须声明所有可能会抛出的checked exception; 在调用这个方法时,必须捕获它的checked exception,不然就得把它的exception传递下去; checked exception是从java.lang.Exception类衍生出来的
5分钟搞懂基因组规模代谢网络(GSMM):从数据库选择到模型构建全流程 本文详细解析基因组规模代谢网络(GSMM)构建的全流程,从数据库选择到模型优化。重点介绍MetaCyc、BiGG等主流数据库的黄金三角评估法则,对比自上而下与自下而上两种建模方法,并提供模型修剪、仿真优化的实用技巧与避坑指南,帮助研究者高效构建精准代谢网络模型。 阅读详情

相关推荐

手把手教你用CODESYS将旧笔记本改造成软PLC(含证书配置避坑指南)

本文提供了一份详尽的指南,教你如何利用CODESYS平台将闲置旧笔记本改造为一台功能完整的软PLC。内容涵盖从硬件评估、系统实时性优化、软件安装与驱动配置,到关键的证书授权管理避坑指南,旨在帮助自动化工程师和爱好者低成本搭建稳定可靠的学习与开发平台。

weixin_29190573的博客 291

运行时异常(RuntimeException)和受检查异常(Checked Exception)的本质区别

[size=medium]最本质的区别是RuntimeException是运行时才会发生的异常, 而受检查异常是编译时异常,编译器会分析哪些异常会在执行一个方法或者构造函数的时候抛出。 异常(Exception):你可以使用运行时异常或者编译时异常。 运行时异常(RuntimeException)也称作未检测的异常(unchecked exception),这表示这种异常不需要编译器来...

Inner peace 2811

Opencv全景图像处理实战:柱面与透视展开技术详解

本文详细解析了使用OpenCV实现全景图像处理的两种核心技术:柱面展开与透视展开。通过原理拆解与实战代码演示,指导开发者将360度环绕的鱼眼或球面图像转换为可用的平面视图,适用于街景展示、车载环视、室内测量等计算机视觉应用场景。

weixin_29081163的博客 588

Java 的两种异常 Checked Exception 与 Runtime Exception

Java 有两种异常: Checked Exception 与 Runtime Exception. 整理了一下两者的区别: 区别 Checked Exception Runtime Exception 基类 java.lang.Exception java.lang.RuntimeException 捕获 强制 不强制 Checked Exception 的基类是 Exception; Runtime Exception 的基类是 RuntimeException (不过 Run

蟹脑板的博客 818

VisionMaster图像源配置全攻略:从本地图片到相机SDK的保姆级教程

本文详细解析了VisionMaster图像源配置的三种主流方式:本地图片、相机直连和SDK集成。从像素格式选择到工业相机触发控制,再到SDK开发实战,提供全面的技术指导和避坑建议,帮助开发者高效实现图像处理应用的部署与优化。

yhn45678901的博客 781

高频仿真:高频天线设计_(4).天线参数分析与优化

通过上述步骤,我们展示了如何综合使用解析方法、数值优化方法和实验数据来设计和优化一个高效宽带天线。首先,我们通过解析方法确定了天线的初步长度;然后,使用遗传算法优化了天线的直径以最大化增益;最后,通过实验数据验证了天线的性能,包括驻波比和带宽。这一综合性方法可以有效地提升天线的设计和优化效果,确保其在实际应用中表现出色。

2401_87715305的博客 927

RuntimeException与CheckedException差异

RuntimeException与CheckedException Java的异常被分为两大类:Checked异常和Runtime异常(运行时异常)。所有RuntimeException类及其子类实例被称为Runtime异常;不是RuntimeException类及其子类的异常实例则称为Checked异常。 只有Java语言提供了Checked异常,其他语言都没有提供Checked异常。Java

LSDNH_123的博客 479

5.17华为OD机试真题 新系统 - 输出二叉树后序遍历结果 (Java/Py/C/C++/Js/Go)

5.17华为OD机试真题 新系统 - 输出二叉树后序遍历结果 (Java/Py/C/C++/Js/Go)

算法大师! 531

Java中编译期异常和运行期异常的区别

在Java中,异常分为运行期异常(Runtime Exception)和编译期异常(Checked Exception),两者的核心区别在于 编译器是否强制要求处理。以下是它们的详细对比: 1. 定义与分类 类别 运行期异常(Runtime Exception) 编译期异常(Checked Exce

fenfenfen520a的博客 92

AUTOSAR进阶图解==>AUTOSAR_SWS_CANStateManager

AUTOSAR CAN状态管理器(CanSM)摘要 CanSM是AUTOSAR通信栈中的关键模块,负责管理CAN网络状态和模式转换。主要功能包括: 控制CAN控制器/收发器工作模式(STARTED/STOPPED,NORMAL/STANDBY) 处理三种网络状态(全通信、静默通信、无通信)之间的转换 监控和处理总线关闭(Bus-Off)事件 与ComM、CanIf、BswM等模块协同工作 CanSM通过状态机管理网络状态转换,支持可配置的总线关闭恢复策略。它为每个CAN网络维护独立的状态机,实现网络状态的精

一名留德华的,康德的信徒的,专注于汽车电子领域的博客 5586

选课系统进不去?我用 Python 做了个“捡漏挂机”脚本,全自动监控空余名额

频率控制:脚本请求频率不要太高(建议间隔 3-5 秒以上),否则可能被教务系统封 IP,甚至会被教务处请喝茶。仅供学习:本文旨在通过选课场景教学requests和网络抓包原理,请勿用于非法用途或破坏公平性。刷新页面 -> 等待加载 -> 用眼睛看人数 -> 没满?-> 点击选课 -> 确认这个流程最大的瓶颈在于**“等待加载”和“人的反应时间”**。网页加载需要渲染 HTML、CSS、图片,而 Python 脚本只需要请求一个微小的 JSON 数据接口,速度是浏览器的10 倍以上。fill:#333;

BUG猿的博客 299

浅析Java语言中两种异常的差别

Java提供了两类主要的异常:runtime exception和checked exception。所有的checked exception是从java.lang.Exception类衍生出来的,而runtime exception则是从java.lang.RuntimeException或java.lang.Error类衍生出来的。   它们的不同之处表现在两方面:机制上和逻辑上。   

首席技术执行官CTO(Chief Technology Officer)|技术总监--邓斌博客 896

YOLO11改进策略【独家融合改进】| RCSOSA + SPD + WFU

SPD-Conv是一种新的 CNN 构建模块,用于替代传统 CNN 架构中使用的步长卷积(strided convolution)和池化(pooling)层,它由空间到深度(Space-to-depth,SPD)层和非步长卷积(non - strided convolution)层组成。WFU模块通过小波变换的频率分解与跨尺度融合机制,解决了传统上采样过程中的混叠和细节丢失问题,实现了高效、高保真的面部细节重建。

Limiiiing的博客 459

java 两种异常_浅析Java语言中两种异常的差别

一起学习Java提供了两类主要的异常:runtime exception和checked exception。所有的checked exception是从java.lang.Exception类衍生出来的,而runtime exception则是从java.lang.RuntimeException或java.lang.Error类衍生出来的。它们的不同之处表现在两方面:机制上和逻辑上。一、机制上...

weixin_29363945的博客 214

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

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

exceptional java_浅析Java语言中两种异常的差别

以及一个使用exception的例子:public class ExceptionalClass{public void method1()throws CheckedException{// ... throw new CheckedException( “...出错了“ );}public void method2( String arg ){if( arg == null ){throw n...

weixin_39976081的博客 286

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

上一篇: JXTA2.3.V Java 编程指南(1)翻译:陈凌晖
下一篇: java数字比较进阶
java169
博客等级 码龄19年 27粉丝 2568原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址