Java checked exception
Created By: chatGPT
In Java, a checked exception is an exception that must be either caught or declared in the method that could throw it. Checked exceptions are derived from the Exception class but are not subclasses of the RuntimeException class. This means that the compiler checks these exceptions at compile-time, ensuring that you handle or declare them explicitly in your code. This is essential for creating robust applications as it forces developers to think about error handling.
try {
// Code that might throw an exception
FileInputStream file = new FileInputStream("path/to/file.txt");
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
}
Common examples of checked exceptions include IOException, SQLException, and ClassNotFoundException. When dealing with these exceptions, you can either handle them using a try-catch block or declare them using the throws keyword in the method signature.
public void readFile(String fileName) throws IOException {
FileInputStream file = new FileInputStream(fileName);
// Further processing
}
Using checked exceptions encourages developers to write cleaner and more maintainable code by anticipating errors that can occur during runtime. It also promotes better practices for error handling, ensuring that all functionalities in your program are covered.
public void connectToDatabase() {
try {
// Code that might throw a SQLException
Connection connection = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
System.out.println("Database connection failed: " + e.getMessage());
}
}