Mark As Completed Discussion

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:

  1. 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.
TEXT/X-JAVA
1try {
2  // code that may throw a checked exception
3} catch (CheckedException e) {
4  // handle the exception
5}
  1. 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.
TEXT/X-JAVA
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.

TEXT/X-JAVA
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.

TEXT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment