Java Programming Techniques and APIs

Checked vs Unchecked Exceptions in Java

Checked vs Unchecked Exceptions in Java

Checked Exceptions

Generally, a checked exception (also called a logical exception) in Java occurs when your code goes wrong and is potentially recoverable.

Suppose we get a client error when calling another API; then, we could retry from that exception and see if it runs again.

The compiler catches checked exceptions at compile time, so if something throws one, the compiler will make sure you handle it. A checked exception represents an error outside of the program's control. FileInputStream, for example, throws a FileNotFoundException if the input file isn't found.

Checked Exception Example Code

import java.io.File;
import java.io.FileInputStream;

public class CheckedExceptionExample {
    public void readFile() {
        String file_Name = "The file does not exist";
        File f= new File(file_Name);
        FileInputStream f_stream = new FileInputStream(f);
    }
}

Output
CheckedExceptionExample.java:8: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
        FileInputStream f_stream = new FileInputStream(f);^1 error.

write your code here: Coding Playground

Therefore, we should declare a checked exception by using the try-catch block.

Try-Catch

A try-catch block wraps the Java code that throws the checked exception. As a result, you can now process and handle the exception.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class CheckedExceptionExample {
    public static void main(String[] args) {
        String file_Name = "file does not exist";
        File f = new File(file_Name);
        try {
            FileInputStream stream = new FileInputStream(f);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}
Output
java.io.FileNotFoundException: file does not exist (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at CheckedExceptionExample.main(CheckedExceptionExample.java:10)

write your code here: Coding Playground

Unchecked Exceptions

Unlike checked exceptions, unchecked exceptions represent errors in programming logic, not erroneous situations that may reasonably occur when using an API.

The compiler cannot anticipate logical errors occurring only at runtime, so it cannot identify these problems at compile time. This is why they are called "unchecked" exceptions. The program won't generate a compilation error even if the programmer doesn't handle an unchecked exception.

Moreover, unchecked exceptions don't have to get declared in methods with throws. It occurs most often when the user provides insufficient or wrong data when interacting with the program. A programmer must determine which conditions will cause such exceptions and take appropriate action accordingly.

The unchecked exception is a direct subclass of the RuntimeException class. In software, unchecked exceptions can arise from faulty logic anywhere in the code.

For example, A NullPointerException occurs if a developer invokes a method on a null object. Unchecked ArrayIndexOutOfBoundsException occurs if an array element does not exist.

Here are some unchecked exception classes:

  • NullPointerException
  • ArrayIndexOutOfBoundsException
  • ArithmeticException
  • IllegalArgumentException
  • NumberFormatException

Unchecked Exception Example

public class Example
  public static void main(String args[])
  {
int num1=10;
int num2=0;
int res=num1/num2;
System.out.println(res);
  }
}

Output
Exception in thread "main" java.lang.ArithmeticException: / by zeroat Example.main(Example.java:6)

write your code here: Coding Playground