Exception Hanlding in Java

Checked and Unchecked Exception and how to handle exceptions in Java.

Checked Exception

Checked exceptions are subclasses of Exception.

Checked Exception are the exceptions that are checked at compile time. If a method throws a checked exception, the caller must handle the exception or declare the exception in the method signature. For example, IOException, SQLException are checked exceptions.

Use checked exceptions when the caller can recover from the exception. For example, if a file is not found, the caller can handle the exception by creating a new file.

Some programming languages like C# and Python do not have checked exceptions. They use unchecked exceptions for all exceptions.

Checked Exception example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class NewCheckedException extends Exception {
public NewCheckedException(String message) {
super(message);
}
}
// throw and declare the checked exception
public void throwCheckedException() throws NewCheckedException {
throw new NewCheckedException("This is a checked exception");
}

// handle the checked exception
public static void main(String[] args) {
try {
throw new NewCheckedException("This is a checked exception");
} catch (NewCheckedException e) {
e.printStackTrace();
}
}

Unchecked Exception(Runtime Exception)

Unchecked exceptions are subclasses of RuntimeException.

Unchecked Exception are the exceptions that are not checked at compile time. If a method throws an unchecked exception, the caller is not required to handle the exception. For example, NullPointerException, ArrayIndexOutOfBoundsException are unchecked exceptions. Unchecked exceptions are usually bubbled up to the top of the call stack.

Use unchecked exceptions when the caller cannot recover from the exception. For example, if a user is not found, the caller cannot recover from the exception.

Unchecked Exception example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String message) {
super(message);
}
}

// throw the unchecked exception
public void throwUncheckedException() {
throw new UserNotFoundException("User not found");
}

// Handle the unchecked exception(not required)
public static void main(String[] args) {
try {
throw new UserNotFoundException("User not found");
} catch (UserNotFoundException e) {
e.printStackTrace();
}
}

Handle Exception

There are a couple of ways to handle exceptions in Java.

  • log the exception and continue if the exception is not critical
  • log and rethrow the exception
  • wrap the exception and rethrow the exception

Remeber not to ignore/swallow the exception.

Checked exception produces a lot of boilerplate code. It is common to wrap the checked exception in an unchecked exception and rethrow the exception.