So, today will be studying Checked Exceptions and Unchecked Exceptions along with the examples for a better understanding of the topic. First, we will learn Exception Handling in Java and its types. After that, we will be learning when and where we should use checked and unchecked exceptions. In the end, we will discuss some major key differences between checked and unchecked exceptions in java.
Exceptions and Exception Handling in Java
Exceptions are events that occur during the execution of a Java program that disrupts the normal flow of the program’s instructions. These events are typically associated with error conditions, such as division by zero or trying to access an index that is out of the bounds of an array, that prevents the program from continuing normal execution.
There are two types of Built-in exceptions in Java: checked exceptions and unchecked exceptions as shown in the image given below:
Exception handling in Java is a mechanism that allows you to handle errors or exceptional conditions that may occur in a program. The process of handling exceptions involves capturing the exception, examining its information, and then taking appropriate action to resolve the error.
In Java, exceptions are thrown by the Java Virtual Machine (JVM) or by the code in a program when an error or exceptional condition occurs. To handle exceptions in Java Programming Language, you use the try-catch statement. The try block contains the code that might throw an exception, and the catch block contains the code that will be executed if an exception is thrown.
Syntax of try-catch block is:
try {
// These statements/code might throw an exception
} catch (ExceptionType e) {
// code to handle the exception
}
It’s also possible to use the finally block to ensure that certain code is executed regardless of whether an exception is thrown or not. The finally block is optional and can be used to release resources or perform other clean-up actions.
In addition to the try-catch statement, Java also provides the throws clause, which can be used to declare that a method may throw a specific exception. This allows the calling code to handle the exception, or to pass the exception up the call stack to the next level of the program.
Now, since we are well equipped with the knowledge of exceptions and the process of Exception Handling in Java, Let’s deep dive into the topic of Checked Exceptions.
What are Checked Exceptions in Java?
In Java, checked exceptions are exceptions that the Java compiler checks for and requires you to handle or declare in your code. Checked exceptions are typically used to indicate a recoverable error, such as when a file cannot be found or a network connection cannot be established.
Checked exceptions are subclasses of the Exception class and, unlike unchecked exceptions, must be either caught and handled or declared in the throws clause of the method where they occur. The Java compiler enforces this requirement by generating a compile-time error if a checked exception is not handled or declared.
IOException, SQLException, and InterruptedException are some examples of Built-in Checked Exceptions in Java.
Examples of Checked Exceptions
Commonly occurring Checked Exceptions are discussed below:
1. IO Exception
This exception is thrown when an input/output operation fails, such as reading from a file that doesn’t exist.
import java.io.*; class Main { public static void main(String[] args) { try { File file = new File("test.txt"); FileReader reader = new FileReader(file); reader.read(); } catch (IOException e) { System.out.println("An IOException occurred: " + e.getMessage()); } } }
Output:
An IOException occurred: test.txt (No such file or directory)
Explanation:
In this example, we are trying to read a file named “test.txt”. Since the file does not exist, it throws an IOException while reading the file. This IOException caught the catch block and the error message is printed to the console.
2. SQL Exception
This exception is thrown when an error occurs while working with a database.
import java.sql.*; class Main{ public static void main (String[] args){ // your code goes here try { Connection connection = DriverManager.getConnection("jdbc:sqlite:test.db"); Statement statement = connection.createStatement(); statement.executeQuery("SELECT * FROM users"); } catch (SQLException e) { System.out.println("A SQLException occurred: " + e.getMessage()); } } }
Output:
A SQLException occurred: No suitable driver found for jdbc:sqlite:test.db
Explanation:
In this example, a connection to an SQLite database is established using the “DriverManager.getConnection” method. The SQL statement "SELECT * FROM users" is then executed using a Statement object. If an error occurs while accessing the database, an SQLException is thrown and caught in the catch block and then we have printed the error message on the console screen.
3. Interrupted Exception
The InterruptedException in Java is thrown when a thread is interrupted.
class Main { public static void main(String[] args) { try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.println("The thread was interrupted."); } } }
Output:
The thread was interrupted.
Explanation:
In this example, the main method is sleeping for one second using the Thread.sleep() method. If the sleep method is interrupted by another thread, the InterruptedException is thrown and caught in the catch block. Then we print the message "The thread was interrupted" on the console screen.
What are Unchecked Exceptions in Java?
In Java, unchecked exceptions are exceptions that the Java compiler does not check. These are typically runtime exceptions that are thrown when a program violates an assumption about the state of the system, such as an index out of bounds or a null pointer exception. Unlike checked exceptions, you do not need to declare or handle unchecked exceptions in your code.
Examples of unchecked exceptions in Java include NullPointerException, ArithmeticException, and ArrayIndexOutOfBoundsException. Unchecked exceptions indicate a bug in the code and should be fixed, rather than simply being handled.
It’s good practice to catch unchecked exceptions and handle them appropriately, as they can still cause your program to crash if left unhandled. However, unlike checked exceptions, you are not required to do so by the Java compiler.
Examples of Unchecked Exceptions
Let us understand some of the commonly occurring Unchecked Exceptions in Java with the help of examples given below:
1. NullPointer Exception
This exception is thrown when an application tries to access an object through a null reference.
class Main { public static void main(String[] args) { try{ String str = null; System.out.println(str.length()); } catch (Exception e){ System.out.println("NullPointerException Occurred: " + e.getMessage()); } } }
Output:
NullPointerException Occurred: null
Explanation:
In this example, a string variable str is declared but not initialized. When the length of the string is attempted to be accessed using the length() method, a NullPointerException is thrown. The “catch” block will catch the exception, then we print the error message on output console.
2. Arithmetic Exception
This exception is thrown when an arithmetic operation such as dividing by zero is performed.
class Main { public static void main(String[] args) { try{ int x = 10; int y = 0; System.out.println(x / y); } catch (Exception e){ System.out.println("ArithmeticException Occurred: " + e.getMessage()); } } }
Output:
ArithmeticException Occurred: / by zero
Explanation:
In this example, an ArithmeticException is thrown when the value of x is divided by y, which has a value of zero. Division by zero is undefined in mathematics and results in an ArithmeticException in Java. The “catch” block will catch the ArithmeticException, then we print the “ArithmeticException Occurred” with the error message on output console.
3. Array Index Out Of Bounds Exception
This exception is thrown when an array is accessed with an index that is outside its bounds.
class Main { public static void main(String[] args) { int[] arr = new int[] {1, 2, 3, 4, 5}; try { System.out.println(arr[5]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("ArrayIndexOutOfBoundsException occurred: " + e.getMessage()); } } }
Output:
ArrayIndexOutOfBoundsException occurred: Index 5 out of bounds for length 5
Explanation:
In this example, an array of integers named “arr” is created and initialized with 5 elements. When an attempt is made to access the 6th element of the array using arr[5], an “ArrayIndexOutOfBoundsException” is thrown. The ArrayIndexOutOfBoundsException is caught in the catch block and a message indicating that the exception has occurred is printed to the console
When to use Checked and Unchecked Exceptions in Java?
In Java, it’s recommended to use checked exceptions when an exception represents a condition that can be reasonably recovered from, while unchecked exceptions should be used for conditions that cannot be recovered from, such as programming errors.
Checked exceptions should be used in cases where the program can reasonably anticipate the exception and take appropriate action to handle it. For example, if a method that reads data from a file, it might throw a FileNotFoundException if the specified file is not found. The calling code can catch this exception and handle it in a meaningful way, such as displaying an error message to the user or prompting them to choose a different file.
Unchecked exceptions should be used in cases where the program cannot reasonably anticipate the exception or where the exception represents a programming error that should be fixed. For example, if a method tries to access an array with an index that is outside the bounds of the array, it will throw an ArrayIndexOutOfBoundsException, which is an unchecked exception. This exception indicates that the program is using the array incorrectly and should be fixed.
It’s important to note that checked exceptions require more boilerplate code to handle since they need to be either caught or declared in the method signature. This can make the code more verbose, but it also forces the developer to think about the potential exceptions that might be thrown and to handle them appropriately. On the other hand, unchecked exceptions are often easier to work with, since they don’t require explicit handling, but they can lead to unexpected behavior if they are not properly handled.
Difference Between Checked and Unchecked Exceptions in Java
Main differences between Checked and Unchecked Exceptions in Java are summarized in the following table:
Feature | Checked Exceptions | Unchecked Exceptions |
---|---|---|
Definition | Exceptions that must be either caught or declared in the method signature. | Exceptions that do not need to be handled. |
Use case | For conditions that can be reasonably recovered from. | For conditions that cannot be recovered from, such as programming errors. |
Propagation | Must be either caught or declared in the method signature. | Can be propagated up the call stack without being caught. |
Coding overhead | More coding overhead due to the requirement to handle or declare exceptions. | Less coding overhead, since exceptions do not need to be handled. |
Example | FileNotFoundException, IOException, SQLException. | NullPointerException, ArrayIndexOutOfBoundsException, IllegalArgumentException. |
Syntax | Must be surrounded by a try-catch block or declared in the method signature. | Do not need to be surrounded by a try-catch block. |
Execution time | Slows down the execution of the program. | Does not slow down the execution of the program. |
Error reporting | Provides more detailed error information. | Provides less detailed error information. |
Maintenance | Easier to maintain since the programmer is forced to handle exceptions. | More difficult to maintain since exceptions are not always handled. |
Performance | Slower performance due to the overhead of handling exceptions. | Faster performance since exceptions does not need to be handled. |
Debugging | Easier to debug, since the exception is clearly defined. | More difficult to debug, since the cause of the exception is not always clear. |
Portability | Portable, since the exception handling mechanism is clearly defined. | Less portable, since the behavior of unchecked exceptions may vary between different implementations. |
Documentation | Better documented, since exceptions are clearly defined. | Less well documented, since unchecked exceptions are often not well defined. |
User experience | Better user experience, since exceptions can be handled and the program can continue executing. | Worse user experience, since exceptions may cause the program to terminate. |
Testability | Easier to test, since exceptions can be clearly defined and handled. | More difficult to test, since exceptions may be propagated up the call stack and not always handled. |
Predictability | More predictable behavior, since exceptions are clearly defined and handled. | Less predictable behavior, since exceptions may be propagated up the call stack and not always handled. |
Conclusion
So, we have learned about Exceptions and Exception Handling in Java. Checked and Unchecked Exceptions have been discussed along with different examples.
After that, we learned when we should use the exception. We have also listed out some major differences between the two types of Exceptions i.e. Checked and Unchecked Exceptions in Java.
Frequently Asked Questions (FAQs)
Here are some common questions and answers regarding checked and unchecked exceptions in Java:
Q: What is the difference between checked and unchecked exceptions in Java?
A: Checked exceptions are exceptions that must be handled in the code or declared in the method signature. Unchecked exceptions are exceptions that are not required to be handled in the code or declared in the method signature.
Q: When should I use checked exceptions?
A: Checked exceptions should be used for exceptional conditions that can be handled and recovered from in the code.
Q: When should I use unchecked exceptions?
A: Unchecked exceptions should be used for exceptional conditions that cannot be handled in the code and represent a programming error, such as a NullPointerException or ArrayIndexOutOfBoundsException.
Q: Are all exceptions in Java checked?
A: No, not all exceptions in Java are checked. Some exceptions, such as RuntimeExceptions, are unchecked exceptions.
Q: Can checked exceptions be propagated through a method chain?
A: Yes, checked exceptions can be propagated through a method chain by declaring the exceptions in the method signature and rethrowing the exception in each method.
Q: How do I handle checked exceptions in Java?
A: Checked exceptions can be handled in Java using a try-catch block or by declaring the exception in the method signature and handling the exception in the method body.