Question: What are Checked Exceptions? Give an example.
Answer:
In Java, Checked Exceptions are exceptions that are checked at compile time by the Java compiler. This means that the compiler enforces the handling of these exceptions, either by using a try-catch
block or by declaring them in the method signature using the throws
keyword.
Characteristics of Checked Exceptions:
- Checked at Compile Time: Checked Exceptions are verified by the compiler during the compilation process.
- Must be Handled: Code that may throw Checked Exceptions must be enclosed within a
try-catch
block or declared to be thrown using thethrows
keyword. - Subclass of Exception: Checked Exceptions are subclasses of the
Exception
class but not subclasses ofRuntimeException
.
Example of Checked Exception:
Consider the FileNotFoundException
, which occurs when attempting to access a file that does not exist:
import java.io.FileReader;
import java.io.FileNotFoundException;
public class Main {
public static void main(String[] args) {
try {
FileReader fileReader = new FileReader("file.txt"); // Attempt to open a file
} catch (FileNotFoundException e) { // Handling FileNotFoundException
System.out.println("File not found: " + e.getMessage());
}
}
}
Explanation:
- In this example, the
FileReader
constructor may throw aFileNotFoundException
if the specified file does not exist. - To handle this checked exception, we enclose the
FileReader
instantiation within atry-catch
block. - If a
FileNotFoundException
occurs, the catch block executes, and an appropriate message is printed.
Benefits of Checked Exceptions:
- Forces Error Handling: Checked Exceptions ensure that developers handle potential error conditions, leading to more robust and reliable code.
- Enhances Code Readability: By explicitly specifying the exceptions that a method may throw, Checked Exceptions improve code documentation and readability.
- Encourages Defensive Programming: Developers are prompted to anticipate and handle exceptional scenarios, resulting in code that gracefully handles error conditions.
Conclusion:
Checked Exceptions in Java provide a mechanism for handling exceptional conditions that may occur during program execution. By enforcing error handling at compile time, Checked Exceptions promote code reliability, maintainability, and robustness.