Java Checked and Unchecked Exceptions

In this Java article we want to learn about Java Checked and Unchecked Exceptions, so in Java programming language, exceptions are the best way for handling runtime errors and exceptional situations that can occur during program execution. there are two types of exceptions in Java, we have checked and unchecked exceptions. in this article we want to learn about differences between checked and unchecked exceptions and how they are handled in Java programming.

 

 

Java Checked Exceptions

Checked exceptions are exceptions that are checked in compile time. this means that Java compiler checks that the code that want to throw a checked exception, it has been handled by a try catch block or declared in the method signature using throws keyword. examples of checked exceptions includes IOException, SQLException and ClassNotFoundException.

 

 

 

This is an example of how to handle a checked exception using try catch block, in this example the code that can throw checked exception is placed in try block. if an IOException is thrown, than the catch block will handle the exception.

 

 

 

Unchecked Exceptions

For unchecked exceptions also we can call runtime exceptions, they are exceptions that are not checked at compile time. these exceptions occurs at runtime and can be caused by different reasons, such as null pointer exceptions, arithmetic exceptions and array index out of bounds exceptions.

 

 

This is an example of unchecked exception:

 

 

This is the code

 

 

This will be the result

Java Checked and Unchecked Exceptions
Java Checked and Unchecked Exceptions

 

 

 

How to Handle Checked and Unchecked Exceptions

Both checked and unchecked exceptions can be handled using try catch block. also the difference is this that checked exceptions must be handled by either try catch block or declared in the method signature using throws keyword, and unchecked exceptions do not need to be declared or handled explicitly.

 

 

This is an example of how to handle checked exception using throws keyword.

In this example readData() method can throw an IOException, so we declare it in the method signature using throws keyword.

 

 

Learn More

Leave a Comment