Checked Exception In Java
In Java, there are two types of exceptions: checked and unchecked exceptions. Checked exceptions are exceptions that the compiler requires to be handled by the caller of a method. This means that when you write a method that can potentially throw a checked exception, you must either catch that exception or declare it in the method signature using the throws
keyword.
Checked exceptions are typically used for exceptional conditions that are outside of the program's control, such as input/output errors, network errors, and database errors. Examples of checked exceptions in Java include IOException
, SQLException
, and ClassNotFoundException
.
When a method throws a checked exception, the caller of the method must either handle the exception using a try-catch
block or declare the exception using the throws
keyword. If the caller chooses to declare the exception using throws
, then the exception will be propagated up the call stack until it is caught by a try-catch
block or until it reaches the top-level of the program, where it will cause the program to terminate.
The use of checked exceptions can help to make programs more robust by forcing developers to handle exceptional conditions that may occur at runtime. However, they can also be a source of code complexity and can make code harder to read and understand. As a result, some developers prefer to use unchecked exceptions in their programs.
Here is an example of a Java program that demonstrates the use of a checked exception:
javaimport java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class CheckedExceptionExample {
public static void main(String[] args) {
File file = new File("example.txt");
try {
FileReader reader = new FileReader(file);
// Do something with the file
} catch (IOException e) {
System.out.println("An error occurred while reading the file: " + e.getMessage());
}
}
}
In this program, we create a File
object that represents a file named "example.txt". We then create a FileReader
object and attempt to read the contents of the file.
Since the FileReader
constructor can throw an IOException
, we wrap the constructor call in a try-catch
block. If an IOException
is thrown, we catch it and print an error message to the console.
This program demonstrates how checked exceptions can help to ensure that exceptional conditions are handled properly, even when dealing with external resources like files.
Comments
Post a Comment