Checked vs Unchecked Exceptions in Java

PROFINET方案选型指南:瑞萨/西门子/开源p-net协议栈对比实测 本文基于瑞萨RZ/N2L硬件平台,对瑞萨官方认证协议栈、西门子ERTECH及开源p-net三种PROFINET方案进行了实测对比。重点分析了PROFINET-IRT实时性、CPU/内存资源消耗、开发集成复杂度及许可证成本等核心指标,为工业设备制造商提供了从性能到商业决策的全面选型指南。 阅读详情

简单说Checked就是在compile阶段会检查,必须用try catch或者throws处理,比如FileNotFoundException

Unchecked就是compile阶段不会检查,比如ArithmeticException 除法(除以0)



In Java, there two types of exceptions:

1) Checked: are the exceptions that are checked at compile time. If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using throws keyword.

For example, consider the following Java program that opens file at locatiobn “C:\test\a.txt” and prints first three lines of it. The program doesn’t compile, because the function main() uses FileReader() and FileReader() throws a checked exception FileNotFoundException. It also uses readLine() and close() methods, and these methods also throw checked exception IOException

import java.io.*;
 
class Main {
    public static void main(String[] args) {
        FileReader file = new FileReader("C:\\test\\a.txt");
        BufferedReader fileInput = new BufferedReader(file);
         
        // Print first 3 lines of file "C:\test\a.txt"
        for (int counter = 0; counter < 3; counter++) 
            System.out.println(fileInput.readLine());
         
        fileInput.close();
    }
}



Output:

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - 
unreported exception java.io.FileNotFoundException; must be caught or declared to be 
thrown
	at Main.main(Main.java:5)

To fix the above program, we either need to specify list of exceptions using throws, or we need to use try-catch block. We have used throws in the below program. Since FileNotFoundException is a subclass of IOException, we can just specify IOException in the throws list and make the above program compiler-error-free.

import java.io.*;
 
class Main {
    public static void main(String[] args) throws IOException {
        FileReader file = new FileReader("C:\\test\\a.txt");
        BufferedReader fileInput = new BufferedReader(file);
         
        // Print first 3 lines of file "C:\test\a.txt"
        for (int counter = 0; counter < 3; counter++) 
            System.out.println(fileInput.readLine());
         
        fileInput.close();
    }
}



Output: First three lines of file “C:\test\a.txt”

2) Unchecked are the exceptions that are not checked at compiled time. In C++, all exceptions are unchecked, so it is not forced by the compiler to either handle or specify the exception. It is up to the programmers to be civilized, and specify or catch the exceptions.
In Java exceptions under Error and RuntimeException classes are unchecked exceptions, everything else under throwable is checked.

                   +-----------+
		   | Throwable |
                   +-----------+
                    /         \
		   /           \
          +-------+          +-----------+
          | Error |          | Exception |
          +-------+          +-----------+
	   /  |  \           / |        \
         \________/	  \______/    	 \
			                +------------------+
	unchecked	 checked	| RuntimeException |
					+------------------+
					  /   |    |      \
					 \_________________/
					   
					   unchecked

Consider the following Java program. It compiles fine, but it throws ArithmeticException when run. The compiler allows it to compile, because ArithmeticException is an unchecked exception.

class Main {
   public static void main(String args[]) {
      int x = 0;
      int y = 10;
      int z = y/x;
  }
}


Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero
	at Main.main(Main.java:5)
Java Result: 1

Why two types?
See Unchecked Exceptions — The Controversy for details.

Should we make our exceptions checked or unchecked?
Following is the bottom line from Java documents
If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception


http://www.geeksforgeeks.org/checked-vs-unchecked-exceptions-in-java/

【Proteus仿真】基于AT89C51单片机的单片机双向通信 本文介绍了基于AT89C51单片机实现双向通信的系统设计。系统采用MAX232芯片实现TTL与RS-232电平转换,通过CONN-D9F接口建立串行通信连接。甲机程序通过按键控制发送不同指令字符,同时接收乙机数据驱动数码管显示;乙机程序根据接收指令控制LED显示状态,并可发送0-10数字至甲机。文中详细说明了MAX232电平转换原理、DB9接口定义,以及完整的单片机控制程序代码,包括串口初始化、数据收发处理等关键功能实现,为嵌入式系统串口通信开发提供了实用参考方案。 阅读详情

相关推荐

汽车底盘技术解析:从悬架调校到智能化,如何评价国产车底盘实力

汽车底盘作为决定车辆驾驶质感、安全性和耐久性的核心系统,其技术内涵远不止于悬架结构。从行驶系、转向系到制动系的协同工作,底盘调校是一门融合机械原理与工程实践的艺术。在电动化与智能化浪潮下,底盘技术正经历从被动适应到主动响应的变革,CDC可变阻尼减震器和空气悬架等技术的应用,让底盘具备了通过OTA升级实现性能优化的可能。国产汽车品牌如奇瑞、吉利等,通过平台化架构研发与调校经验积累,正推动底盘技术从“能用”向“好用”乃至“塑造独特驾驶风格”迈进。理解底盘技术,需超越简单的结构对比,关注其在实际路况中的滤震性、支

weixin_34413103的博客 385

java 字符串异常_如何在java中修复字符串太长的异常

我有一个分析字符串的算法,但它只需要大约10000个字符,它将抛出异常Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - constant string too long这是我使用的代码public static void printRepeatingStrings(String inp...

weixin_39829307的博客 753

蛋白质组学进阶指南 | (八)差异蛋白筛选与功能解析实战

本文是蛋白质组学差异蛋白筛选与功能解析的实战指南。详细讲解了如何利用R语言的limma包进行差异表达分析,结合FDR校正和差异倍数设定筛选关键蛋白,并通过火山图可视化结果。进一步介绍了使用clusterProfiler进行GO与KEGG功能富集分析,以及利用STRING数据库和Cytoscape构建蛋白互作网络以识别枢纽分子,最终串联分析形成可验证的生物学假说。

weixin_29208077的博客 740

解决hive启动异常:Exception in thread "main" java.lang.RuntimeException

Exception in thread "main" java.lang.RuntimeException: The root scratch dir: hdfs://master:8020/hive/scratchdir on HDFS should be writable. Current permissions are: rwx------         at org.apache.had...

hr786250678的博客 1万+

Android音频子系统分析-car_audio_configuration.xml

先附上一个例子,再逐一解释。概括来说,该文件描述了车里有哪些区域,每个区域划分了多少组,每个组包含了哪些设备,每个设备接收哪些类型的音频流。

不定时记录分享一些有用没用的东西 989

STM32实战篇:使用USART发送/接收数据

在发送字符时也可以直接使用其对应的ASCLL码,例如: USART_SendData(USART1, 0x61);

qq_74114817的博客 596

Exception in thread "main" java.lang.RuntimeException:

启动hive时报错:dblab@dblab-virtual-machine:/usr/local/hive$ hiveLogging initialized using configuration in jar:file:/usr/local/hive/lib/hive-common-1.2.1.jar!/hive-log4j.propertiesException in thread "main...

亡月杂货铺 2万+

CTF实战:从ECDSA签名漏洞到flag获取

本文详细解析了ECDSA签名算法在CTF比赛中的实战应用,重点探讨了随机数重用和参数泄露等常见漏洞。通过PWNHUB六月赛的例题,展示了如何从签名数据中恢复私钥并获取flag,同时提供了防御措施和实战技巧,帮助参赛者提升解题能力。

weixin_42706667的博客 277

hive 启动时报错: Exception in thread "main" java.lang.RuntimeException: java.lang.

might have disabled stack guard. The VM will try to fix the stack guard now. It's highly recommended that you fix the library with 'execstack -c ', or link it with '-z noexecstack'. Exception in thr

foxchopin的博客 1万+

【回答问题】ChatGPT上线了!如何安装python-ipopt?python-ipopt有哪些用法?

python-ipopt是一种基于Python语言的求解非线性最优化问题的软件包。它使用了Interior Point Optimizer(IPOPT)算法来求解最优化问题。这段代码使用python-ipopt求解了一个无约束的非线性最小化问题,其目标函数为(x[0] - 1) ** 2 + (x[1] - 2) ** 2,求解结果为x_opt。求解线性规划问题、二次规划问题、二次范数最小化问题等类型的最优化问题。对于给定的最优化问题,可以设置不同的求解参数来控制求解的精度和效率。

源代码杀手的博客 2144

机器学习实战26-一种基于LightGBM的股市涨跌预测系统与代码实现过程

在全球经济一体化的背景下,股市作为经济活动的晴雨表,其波动与预测对于投资者、金融机构乃至国家政策制定者而言至关重要。随着金融市场的日益复杂化与信息量的爆炸式增长,股市分析不再仅限于基本面和技术面的传统研究,而是迫切需要更加精准、高效及智能化的方法来捕捉市场动态,以辅助决策制定。模型评估是确保LightGBM股市预测系统准确性和稳定性不可或缺的一环。通过综合运用多种评估指标、科学的验证方法以及深入的性能分析,我们不仅能够全面理解模型的能力和限制,还能为持续优化模型、提升预测准确性奠定坚实基础。

微学AI的博客 2327

Exception in thread “main“ java.lang.RuntimeException: java.lang.ClassNotFoundException

今天做测试的两次遇到这个错,特此记录一下,以免再犯。 发生这个问题的原因是因为我自己的疏忽,做代码自动生成测试时,忘在pom文件中加mysql驱动相关的依赖,导致没有对应的jar包报错 网上搜寻了有关这个异常的内容 关于这个异常的说明如下 无法找到指定的类异常。 当应用程序试图使用以下方法通过字符串名加载类时,抛出该异常: ** Class 类中的 forName 方法。 ClassLoader 类中的 findSystemClass 方法。 ClassLoader 类中的 loadClass 方法。**

是苹果没错了 3966

高速PCB设计中的一些常用规则

目前,高速PCB产品设计中,高速接口的应用日益普及,对于复杂的设计而言,高速走线就如同“蜘蛛网”一样密布在PCB各处,因此,在进行PCB检查及评审时,必要的高速PCB设计经验法则及规则是工程师开展工作必不可少的知识储备。

一只豌豆象的博客 3414

Checked and Unchecked Exceptions in Java

Checked exceptions: exceptions that are checked at compile time. 所以需要在方法上throws异常,或者用try-catch来处理异常,不然编译器会报错。Checked exceptions表示在正常work flow之外的错误。 // throws keyword private static void checkedExceptionWithThrows() throws FileNotFoundException { File f

jzhong720的博客 184

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

java 异常选择: Checked Exception VS Unchecked Exception

Checked Exception 设计的初衷是为了从异常情况恢复,Checked Exception 假使我们捕获了异常,然后需要恢复程序 Unchecked Exception 运行时异常,类似 NullPointerException、ArrayIndexOutOfBoundsException ,通常是编码可以避免的逻辑错误,不可恢复 Checked Exception VS Unchecked Exception 支持 Checked Exception 编译器强制检查,Checked Exce

qq_14957991的博客 369

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

exhaustion java_Java Exceptions

1. 常见错误分类一般的,errors可以分为以下几类:user input errorsdevice errors or physical limitationscode errors2. 常用错误处理方式2.1 error code一种常用的错误处理方法是返回error code,由calling method根据error code做不同处理。但是有些情形下error code并不方便使用,...

weixin_39688170的博客 84

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

Checked Exception vs Unchecked Exception

Unchecked exceptions are the run-time errors that occur because of programming errors, such as invalid arguments passed to a public method. The Java compiler does not check the unchecked exceptions d...

helloworld的专栏 603

Exceptions in Java and C#

头绪太多,整理中...在Java中,Exception分为checked, unchecked两类。对于checked exception,如果一个方法在内部抛出了checked exception,那就必须在方法签名中申明它;而调用这个方法的其他方法,要么必须处理这个checked xception,要么就要重新申明并抛出同样的exception。而对于unchecked exception来说

wangjiong的专栏 1042

Checked exception及Unchecked exception对比

从异常处理机制的角度可以分为两类,Unchecked Exceptions和Checked Exceptions。Check即编译器检查程序是否已经抛出或处理了可能的异常。Unchecked Exceptions指的是被程序员check的异常,Checked Exceptions指的是被编译器check的异常。 Throwable下面有两个子类,分别为Error和Exception,其中所有的Error类和Exception类中的RuntimeException类都属于Unchecke

inexaustible的博客 878

unchecked Exception & checked Exception

一.异常介绍任何的异常都是Throwable类,并且在它之下包含两个字类Error / Exception,而Error仅在当在Java虚拟机中发生动态连接失败或其它的定位失败的时候,Java虚拟机抛出一个Error对象。典型的简易程序不捕捉或抛出Errors对象,你可能永远不会碰到需要实例化Error的应用,那就让我们关心一下Exception。Unchecked Exception.:

黄瓜和土豆的专栏 7955

关于checked exception & unchecked exception(RuntimeException)

近日开发百度sdk,用到自定义异常,只是按照原来的学的,只是继承自Exception,没有深思下去。看了一点百度官方的sdk源码,看到里面有方法内有抛出异常,但是方法却没有抛出异常,甚是纳闷。后来想了想,有checkedexception和uncheckedexception之分。所谓checkedexception就是必须手动trycatch或者t...

weixin_34268169的博客 188

checked vs unchecked exception explanation

down vote原文链接:https://stackoverflow.com/questions/6115896/java-checked-vs-unchecked-exception-explanationdown vChecked Exceptions :The exceptions which are checked by the compiler for smooth execution...

thlzjfefe的博客 199

Java Exceptions

1. 常见错误分类 一般的,errors可以分为以下几类: user input errors device errors or physical limitations code errors 2. 常用错误处理方式 2.1 error code 一种常用的错误处理方法是返回error code,由calling method根据error code做不同处理。 但是有些情形下error c...

liuxuhelloworld 179

java exception 非检查异常_Java:已检查vs未经检查的异常说明

以上是否被认为是一个经过检查的例外?不,你是处理异常的事实并不使它成为一个Checked Exception如果它是一个RuntimeException。是RuntimeException一个unchecked exception?是Checked Exceptions是subclasses的java.lang.ExceptionUnchecked ExceptionsAREsubclasse...

weixin_31041955的博客 123

java面试题总结(三)----本文都是笔试题,值得学习

1. 下面哪些是Thread类的方法() A start() B run() C exit() D getPriority() 答案:ABD 解析:看Java API docs吧:http://docs.oracle.com/javase/7/docs/api/,exit()是System类的方法,如System.exit(0)。 2. 下面关于j...

ywl470812087的博客 11万+

Top 10 Questions about Java Exceptions--reference

reference from:http://www.programcreek.com/2013/10/top-10-questions-about-java-exceptions/ This article summarizes the top 10 frequently asked questions about Java exceptions. 1. Checked vs. Uncheck...

weixin_34100227的博客 98
上一篇: LeetCode 判断一个数是否为平衡二叉树 Balanced Binary Tree
下一篇: [多图]美国实习薪水最高的20家科技公司
chiiis
博客等级 码龄14年 422粉丝 429原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值