Java: Checked & Unchecked Exceptions

Unchecked exceptions: Classes that are direct or indirect subclasses of RuntimeException, typically caused by defects in code. 

E.g. ArrayIndexOutOfBoundExceptions, ArithmeticExceptons.

Classes that inherit directly or indirectly from Error (serious abnormal situations in JVM, application program should not attempt to deal with) are unchecked, too.

Unlike checked exceptions, Java does not examine whether an unchecked exception is caught or declared because they typically can be prevented by proper coding.

-- Although the compiler does not enforce it, it’s still better to provide exception-handling code when it’s known that such exceptions might occur. E.g. program should handle NumberFormatException from Integer method parseInt, even though NumberFormatException is checked exception.

 

Checked exceptions: Classes that inherit from Exception but not directly or indirectly from RuntimeException, typically caused by conditions that are not under the control of the program.

e.g. for file processing, when the program cannot open a file that doesn’t exist.

 

Catch-or-declare requirement: The compiler verifies that the checked exception is caught or is declared in a throws clause, an error message will be issued if it’s not satisfied.

1) The code that generates the exception must be wrapped in a try block and must provide a catch handler for the checked-exception type (or its superclasses);

2) The method containing the code that generates the exception must provide a throws clause containing the checked-exception type after its parameter list and before its method body. (If the exception can be handled inside the method then there’s no need to declare throws, just catch to handle it.)

Notice: If a subclass overrides a superclass’s method, subclass method cannot list more exceptions in its throws clause than the superclass method does, but can contain a subset of the superclass’s throws clause.

转载于:https://www.cnblogs.com/RDaneelOlivaw/p/11260745.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值