Java Checked Exceptions
Introduction
Checked
exceptions in Java are exceptions that are checked at compile-time. These
exceptions must be either caught using a try-catch block or declared in the method
signature using the throws keyword. Checked exceptions are typically
used for conditions from which recovery is possible, such as file I/O errors or
network issues.
Table of Contents
1.
What are
Checked Exceptions?
2.
Difference
Between Checked and Unchecked Exceptions
3.
Common
Checked Exceptions
4.
Declaring
Checked Exceptions
5.
Handling
Checked Exceptions
6.
Creating
Custom Checked Exceptions
7.
Best
Practices for Using Checked Exceptions
8.
Real-World
Analogy
9.
Example:
Comprehensive Usage of Checked Exceptions
10. Conclusion
1. What are Checked Exceptions?
Checked
exceptions are exceptions that must be either caught or declared in the method
signature. They represent conditions that a reasonable application might want
to catch. Checked exceptions are subclasses of Exception but not subclasses of RuntimeException.
2. Difference Between Checked and
Unchecked Exceptions
|
Feature |
Checked
Exceptions |
Unchecked
Exceptions |
|
Compile-time Check |
Yes |
No |
|
Declaration Required |
Yes |
No |
|
Subclass of |
Exception |
RuntimeException or Error |
|
Typical Use |
Conditions from which recovery
is possible |
Programming errors, such as
logic errors |
3. Common Checked Exceptions
Some
common checked exceptions in Java include:
- IOException
- SQLException
- FileNotFoundException
- ClassNotFoundException
- InterruptedException
4. Declaring Checked Exceptions
To
declare a checked exception in a method signature, use the throws keyword.
Example:
import java.io.*;
public class CheckedExceptionExample {
public static void main(String[] args) {
try {
readFile("example.txt");
} catch (IOException e) {
System.out.println("IOException caught: " + e.getMessage());
}
}
static void readFile(String fileName) throws IOException {
FileReader file = new FileReader(fileName);
BufferedReader reader = new BufferedReader(file);
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
}
Output:
IOException caught: example.txt (No such file or directory)
5. Handling Checked Exceptions
Checked
exceptions can be handled using a try-catch block.
Example:
public class HandleCheckedException {
public static void main(String[] args) {
try {
readFile("example.txt");
} catch (IOException e) {
System.out.println("IOException caught: " + e.getMessage());
}
}
static void readFile(String fileName) throws IOException {
FileReader file = new FileReader(fileName);
BufferedReader reader = new BufferedReader(file);
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
}
Output:
IOException caught: example.txt (No such file or directory)
6. Creating Custom Checked Exceptions
Custom
checked exceptions are created by extending the Exception class.
Example:
public class CustomCheckedExceptionExample {
public static void main(String[] args) {
try {
validateAge(15);
} catch
(InvalidAgeException e) {
System.out.println("Caught custom checked exception: " + e.getMessage());
}
}
static void validateAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age must be at least 18.");
} else {
System.out.println("Access granted.");
}
}
}
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
Output:
Caught custom checked exception: Age must be at least 18.
7. Best Practices for Using Checked
Exceptions
1.
Use
Meaningful Messages:
Provide detailed and specific error messages.
2.
Catch
Specific Exceptions: Catch
specific exceptions rather than a generic Exception.
3.
Handle
Gracefully: Handle
exceptions in a way that allows the application to continue or provide
meaningful feedback to the user.
4.
Avoid
Overuse: Use
checked exceptions sparingly and only when it is meaningful to enforce
exception handling at compile-time.
5.
Log
Exceptions: Log
exceptions for debugging and auditing purposes.
8. Real-World Analogy
Consider
a scenario where you are booking a flight:
- Checked Exception: Situations like invalid credit card information or a passport
that has expired. These are conditions that need to be checked and handled
to proceed with the booking.
- Unchecked Exception: Situations like a logic error in the booking software. These are
programming errors that should be fixed by the developer.
9. Example: Comprehensive Usage of
Checked Exceptions
Example:
import java.io.*;
public class ComprehensiveCheckedExceptionExample {
public static void main(String[] args) {
try {
processFile("example.txt");
} catch
(FileProcessingException | IOException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
static void processFile(String fileName) throws FileProcessingException, IOException {
if (!new File(fileName).exists())
{
throw new FileProcessingException("File not found: " + fileName);
}
FileReader file = new FileReader(fileName);
BufferedReader reader = new BufferedReader(file);
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
}
class FileProcessingException extends Exception {
public FileProcessingException(String message) {
super(message);
}
}
Output:
Exception caught: File not
found: example.txt
10. Conclusion
Checked exceptions in Java are an essential
mechanism for handling error
conditions from which recovery is possible.
o By using checked exceptions, you can
ensure that your code handles these conditions gracefully and provides
meaningful feedback to the user.
o Understanding how to declare, throw,
and catch checked exceptions, as well as creating custom checked exceptions, is
crucial for writing robust and maintainable Java applications.
No comments:
Post a Comment