Checked vs Unchecked Exceptions
In Java, exceptions can be classified into two types: checked exceptions and unchecked exceptions.
Checked Exceptions
Checked exceptions are exceptions that are checked at compile-time. This means that the compiler will enforce the handling of checked exceptions.
Handling Checked Exceptions
When dealing with a checked exception, you have two options:
- Handle the exception: You can use a
try-catch
block to catch the exception and handle it appropriately. This includes logging the exception, displaying an error message, or taking alternative actions to recover from the exception.
1try {
2 // code that may throw a checked exception
3} catch (CheckedException e) {
4 // handle the exception
5}
- Declare the exception: You can declare the exception by adding it to the method signature using the
throws
keyword. This signals to the calling code that the method may throw this exception and it needs to be handled or declared.
1public void myMethod() throws CheckedException {
2 // code that may throw a checked exception
3}
Unchecked Exceptions
Unchecked exceptions are exceptions that are not checked at compile-time. These exceptions are usually caused by programming errors or unexpected conditions in the code.
Handling Unchecked Exceptions
Unlike checked exceptions, there is no requirement to handle or declare unchecked exceptions. However, it is considered good practice to catch and handle unchecked exceptions that you anticipate may occur.
Example
Let's consider an example where we attempt to divide two numbers. If the divisor is zero, it will throw an ArithmeticException
, which is an unchecked exception.
1public class Main {
2 public static void main(String[] args) {
3 try {
4 int result = divide(10, 0);
5 System.out.println("Result: " + result);
6 } catch (ArithmeticException e) {
7 System.out.println("Error: " + e.getMessage());
8 }
9 }
10
11 public static int divide(int dividend, int divisor) {
12 if (divisor == 0) {
13 throw new ArithmeticException("Division by zero is not allowed.");
14 }
15 return dividend / divisor;
16 }
17}
In this example, we attempt to divide 10 by 0, which causes an ArithmeticException
to be thrown. We catch the exception in a try-catch
block and handle it by printing an error message.
Understanding the difference between checked and unchecked exceptions is important for writing robust and maintainable code.
xxxxxxxxxx
public class Main {
public static void main(String[] args) {
try {
int result = divide(10, 0);
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
}
public static int divide(int dividend, int divisor) {
if (divisor == 0) {
throw new ArithmeticException("Division by zero is not allowed.");
}
return dividend / divisor;
}
}