Java Convert Checked to Unchecked

We can’t convert checked to unchecked or unchecked to checked exception. But we can encapsulate checked exception into unchecked exception and vise versa . By catching checked exception and encapsulating into unchecked exception we will get the feel of converting checked to unchecked. But really we are not converting exception here, we are just encapsulating checked into unchecked.

In spring framework in most of the modules, they will catch checked exception and they will encapsulate checked exception into unchecked exception and then they will throw unchecked exceptions to the callers.

Example 01 : Encapsulate checked exception into unchecked exception

Output :

main begin
checked exception triggering
catched CheckedException, convert into UnCheckedException
catched UnCheckedException
com.vidvaan.corejava.exception25.convert.UnCheckedException: unchecked exception
at com.vidvaan.corejava.exception25.convert.Example01EncapsulateCheckedIntoUncheckedException.encapsulateCheckedIntoUnchecked(Example01EncapsulateCheckedIntoUncheckedException.java:25)
at com.vidvaan.corejava.exception25.convert.Example01EncapsulateCheckedIntoUncheckedException.main(Example01EncapsulateCheckedIntoUncheckedException.java:10)
Caused by: com.vidvaan.corejava.exception25.convert.CheckedException: checked exception
at com.vidvaan.corejava.exception25.convert.Example01EncapsulateCheckedIntoUncheckedException.checkedExceptionMethod(Example01EncapsulateCheckedIntoUncheckedException.java:32)
at com.vidvaan.corejava.exception25.convert.Example01EncapsulateCheckedIntoUncheckedException.encapsulateCheckedIntoUnchecked(Example01EncapsulateCheckedIntoUncheckedException.java:21)
… 1 more
main end

In the above example, We are catching checked exception and encapsulate into unchecked. Even we can do vice versa as shown in the following example.

Example 02 : Encapsulate unchecked exception into checked exception

Output :

main begin
unchecked exception triggering
catched UnCheckedException, convert into CheckedException
catched CheckedException
com.vidvaan.corejava.exception25.convert.CheckedException: checked exception
at com.vidvaan.corejava.exception25.convert.Example02EncapsulateUncheckedIntoCheckedException.encapsulateCheckedIntoUnChecked(Example02EncapsulateUncheckedIntoCheckedException.java:25)
at com.vidvaan.corejava.exception25.convert.Example02EncapsulateUncheckedIntoCheckedException.main(Example02EncapsulateUncheckedIntoCheckedException.java:10)
Caused by: com.vidvaan.corejava.exception25.convert.UnCheckedException: unchecked exception
at com.vidvaan.corejava.exception25.convert.Example02EncapsulateUncheckedIntoCheckedException.uncheckedExceptionMethod(Example02EncapsulateUncheckedIntoCheckedException.java:32)
at com.vidvaan.corejava.exception25.convert.Example02EncapsulateUncheckedIntoCheckedException.encapsulateCheckedIntoUnChecked(Example02EncapsulateUncheckedIntoCheckedException.java:21)
… 1 more
main end

Scroll to Top