关闭

Java - Checked vs Unchecked Exception

288人阅读 评论(0) 收藏 举报

http://javarevisited.blogspot.de/2011/12/checked-vs-unchecked-exception-in-java.html

Sometimes I can't open this page without proper proxy configuration, so I have to copy the content here.


What is Checked Exception in Java?

Checked Exception in Java is all those Exception which requires being catches and handled during compile time. If Compiler doesn’t see try or catch block handling a Checked Exception, it throws Compilation error.

All the Exception which are direct sub Class of Exception but not inherit RuntimeException are Checked Exception.
Example of checked Exception in Java API

IOException
SQLException
DataAccessException
ClassNotFoundException
InvocationTargetException

What is Unchecked Exception in Java?

Unchecked Exception in Java is those Exceptions whose handling is not verified during Compile time. Unchecked Exceptions mostly arise due to programming errors like accessing method of a null object, accessing element outside an array bonding or invoking method with illegal arguments. In Java, Unchecked Exception is direct sub Class of RuntimeException.

What is major benefit of Unchecked Exception is that it doesn't reduce code readability and keeps the client code clean.

Example of unchecked Exception in Java API

NullPointerException
ArrayIndexOutOfBound
IllegalArgumentException
IllegalStateException

Difference between Checked and Unchecked Exception in Java

1) Checked Exception is required to be handled by compile time while Unchecked Exception doesn't.

2) Checked Exception is direct sub-Class of Exception while Unchecked Exception are of RuntimeException.

3) CheckedException represent scenario with higher failure rate while UnCheckedException are mostly programming mistakes.

相同点:

Both Checked and Unchecked Exception are handled using keyword try, catch and finally.

Improved exception handling using multi-catch block (JDK 1. 7 feature)

With JDK7 multi catch block we can catch multiple exception in one catch block separated by pipe (|) and reduce the code duplication.


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:36719次
    • 积分:665
    • 等级:
    • 排名:千里之外
    • 原创:14篇
    • 转载:119篇
    • 译文:0篇
    • 评论:1条
    最新评论