Tuesday 23 July 2013

What is the difference between Checked and Unchecked Exception in Java?



Checked Exception: - All the exceptions which required to be catches and handled at the compile time otherwise a compilation error will be given are known as the checked exception. All checked exception is direct sub Class of Exception but not inherit RuntimeException.
Checked Exception are helpful in ensuring that programmer provide recovery strategy or at least handle the scenario gracefully which can fail the program execution.

Type of checked Exception:-
Following are some Examples of Checked Exception:

1.       IOException
2.       SQLException
3.       DataAccessException
4.       ClassNotFoundException
5.       InvocationTargetException

Advantages and Disadvantages of Checked Exception:-

1.       They help to execute the program by handling some known failure situations.
2.       In long programs, we can location and type of error by handling the proper exceptions.
3.       They are useful in writing the log files for a program.
4.       They make the code complex and less readable

Unchecked Exception:-
All the exceptions whose handling cannot be handled at compile time are known as the Unchecked Exceptions. They mostly arise due to programming errors like accessing method of a null object, accessing element outside an array boundary.  Unchecked Exceptions are direct sub Class of RuntimeException.

Types of Unchecked Exception:-
Here are few examples of Unchecked Exception:

1.       NullPointerException
2.       ArrayIndexOutOfBound
3.       IllegalArgumentException
4.       IllegalStateException


Some Important points:
1. Both Checked and Unchecked Exception are handled using keyword try, catch and finally.
2. In terms of Functionality Checked and Unchecked Exception are same.
3. Checked Exception handling verified during compile time.
4. Unchecked Exception are mostly programming errors
5. JDK7 provides improved Exception handling code with catching multiple Exception in one catch block and reduce amount of boiler plate code required for exception handling in Java.

No comments:

Post a Comment