Checked and Unchecked Exceptions: An Interesting Tale of the Duo!

In Java, there are two types of exceptions in Java: checked exceptions and unchecked exceptions. Checked exceptions are exceptions that must be handled by the method that throws them, or by one of the methods that call it. Unchecked exceptions are exceptions that do not have to be handled, and they have propagated up the call stack until they are handled by a catch block or until they reach the main() method.

Examples of Checked and Unchecked Exceptions

Checked Exceptions

  • IOException: This exception is thrown when an input/output operation fails. For example, if you try to read from a file that does not exist, an IOException will be thrown.
  • SQLException: This exception is thrown when a database operation fails. For example, if you try to insert a row into a table that does not exist, an SQL exception will be thrown.
  • ClassNotFoundException: This exception is thrown when a class cannot be found. For example, if you try to create an object of a class that does not exist, a ClassNotFoundException will be thrown.

Unchecked Exceptions

  • ArithmeticException is thrown when an arithmetic operation results in an impossible result, such as dividing by zero.
  • NullPointerException is thrown when a reference to an object is null and an attempt is made to use the object.
  • ArrayIndexOutOfBoundsException is thrown when an attempt is made to access an element of an array that is out of bounds.
  • NumberFormatException is thrown when an attempt is made to convert a string to a numeric value that is not in the correct format.
  • InputMismatchException is thrown when an attempt is made to read input from a user that is not in the correct format.

How to Handle Checked and Unchecked Exceptions

The throw and throws keywords can be used to handle both checked and unchecked exceptions. However, the throws keyword can only be used to declare checked exceptions. We have covered this topic in detail in our other blog Exception handling in Java: Everything you need to know. please check it out.

Best practices for handling checked exceptions

Use checked exceptions for recoverable errors

Checked exceptions are designed to be used for errors that can be recovered from. For example, if a file cannot be opened, the calling code can try to open a different file or prompt the user for a different file name.

Do not use checked exceptions for programming errors

Programming errors, such as null pointer exceptions, should not be checked exceptions. These errors are usually caused by a bug in the code and cannot be recovered.

Use a try-catch block to handle checked exceptions

When a checked exception is thrown, the calling code must handle it using a try-catch block. If the exception is not handled, the program will crash.

Log the exception and rethrow it

When a checked exception is caught, it is a good practice to log the exception and then rethrow it. This will help you track down the source of the error.

Do not swallow or eat exceptions

It is a bad practice to swallow exceptions. Swallowing an exception means that you are not handling the exception and the program will continue to run even though there is an error. This can lead to unexpected behavior and can make it difficult to track down errors.

Use descriptive exception messages

When you throw a checked exception, it is important to provide a descriptive message that explains the cause of the exception. This will help the calling code, handle the exception appropriately.

Use a consistent Exception Handling style. 

It is helpful to develop a consistent exception handling style for your code. This will make your code easier to read and maintain.

Test your Exception Handling code

It is important to test your exception handling code to make sure that it is working correctly. This will help you to catch any errors in your exception handling code.

Best practices for handling unchecked exceptions

Log the exception

This will help you track down the source of the error and fix it.

Don’t bury thrown exceptions

If you don’t handle an exception, it will be propagated up the call stack until it reaches a method that can handle it. This can lead to unexpected behavior and make it difficult to track down the source of the error.

Use a global exception handler

This is a good way to catch and handle exceptions that are not handled by the specific code that generated them.

Don’t close resources manually

This can lead to resource leaks. Instead, use the try-with-resources statement to automatically close resources when they are no longer needed.

Throw early and handle exceptions late

This is a good way to prevent cascading errors. If you throw an exception early, it will be handled by the code that is closest to the source of the error. This will make it easier to track down the source of the error and fix it.

Use specific exception types whenever possible

This will make your code more readable and maintainable.

Don’t catch too many exceptions

If you catch too many exceptions, you may prevent errors from bubbling up to the code that can actually handle them.

Use the finally block to clean up resources

This will ensure that resources are closed even if an exception is thrown.

Don’t use exceptions for control flow

Exceptions should only be used to handle unexpected errors. If you are using exceptions for control flow, you should consider using other programming constructs, such as conditional statements.

Are unchecked exceptions also called Runtime exceptions?

This is a very tricky question sometimes asked in the Java Interview Questions.

No, unchecked exceptions are not the same as runtime exceptions. Runtime exceptions are a subset of unchecked exceptions.

As we already know by now, in Java, there are two types of exceptions: checked exceptions and unchecked exceptions. Checked exceptions are exceptions that must be declared in the method signature. Unchecked exceptions are exceptions that do not need to be declared in the method signature.

Runtime exceptions are a subset of unchecked exceptions. Runtime exceptions are exceptions that occur at runtime, and they are not caused by programming errors. For example, an ArrayIndexOutOfBoundsException is a runtime exception.

Here is a table that summarizes the differences between checked exceptions, unchecked exceptions, and runtime exceptions:

Type of ExceptionDeclared in Method Signature?Occurs at Runtime?Caused by Programming Error?
Checked ExceptionYesNoYes
Unchecked ExceptionNoYesNo
Runtime ExceptionNoYesNo

It is important to note that not all runtime exceptions are unchecked exceptions. For example, an AssertionError is a runtime exception that is caused by a programming error.

Conclusion

In general, it is considered good practice to handle checked exceptions. This will help to prevent errors from propagating up the call stack and causing problems in other parts of your code. Unchecked exceptions should be handled with care, as they may indicate a serious problem with your code.

Further Readings

Feel free to share your thoughts on this topic in the comments section below 👇 We would be happy to hear and discuss the same 🙂

Spread the word!
0Shares

Leave a comment

Your email address will not be published. Required fields are marked *

One thought on “Checked and Unchecked Exceptions: An Interesting Tale of the Duo!”