Java checked and unchecked exceptions example

Java checked vs unchecked exceptions:

In this post, we will learn the differences between checked and unchecked exceptions in Java. I will also give an introduction to exceptions and how exceptions are handled with different examples.

A brief intro to Exceptions:

An exception disrupts the flow of a program in Java. The Throwable class in Java is the parent class of all exceptions. The exception object holds the information about the cause. An exception can be raised in different scenarios. Suppose the program is trying to open a file but the file is not available, user entered an invalid value etc.

If an exception is not handled, it will terminate the program abnormally. So, we should always handle a code block that might throw an exception.

Handling an exception in Java:

To handle exceptions, try-catch block is used. It is defined as:

try{
    // code that is prone to throw exception
}catch(<Name of Exception> e){
    // catch block
}

If the code written inside the try block throws an exception, it will not terminate the program. Instead, it will move to the catch block and the rest of the program will run normally.

Exception handling is useful in many ways. For example, we can show a meaningful message to the user instead of terminating the program or we can use a different way to fix this.

We can also use multiple catch blocks.

try{
    // code that is prone to throw exception
}catch(<Name of Exception1> e1){
    // catch block for exception 1
}catch(<Name of Exception2> e2){
    // catch block for exception 2
}catch(<Name of Exception3> e3){
    // catch block for exception 3
}

This is useful to handle different type of exceptions.

Checked and Unchecked exceptions:

Exceptions are categorized into:

  • Checked exceptions and
  • Unchecked exceptions

Checked exceptions:

Checked exceptions are also called compile-time exceptions. These exceptions should be handled in the program. A few examples of checked exceptions are FileNotFoundException, ClassNotFoundException, SQLException etc.

These are also called compile-time exceptions because the compiler will show a warning if we don’t handle these exceptions.

Let’s take a look at the below example:

import java.io.FileReader;

public class Main {
    public static void main(String[] args) {
        FileReader fileReader = new FileReader("hello.java");
    }
}

This example is using a java.io.FileReader class to open a file. Your code editor will show one compile-time error:

Java checked exception example

If you hover over the FileReader word, it will show that Unhandled exception: java.io.FileNotFoundException i.e. we have to handle the exception for FileNotFoundException. This exception is thrown if the file is not found or for some other reason, it couldn’t open the file.

To make the code work, we can use a try-catch block to handle this.

import java.io.FileNotFoundException;
import java.io.FileReader;

public class Main {
    public static void main(String[] args) {
        try {
            FileReader fileReader = new FileReader("hello.java");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

Unchecked exceptions:

Unchecked exceptions are also called Runtime exceptions. These are not checked by the compiler. So, even if we don’t handle them, these exceptions will work. For example, ArithmeticException, ClassCastException are unchecked exceptions.

For example,

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.println("Enter a number: ");
        int firstNumber = sc.nextInt();

        System.out.println("Enter another number: ");
        int secondNumber = sc.nextInt();

        System.out.println("The result of first-number/second-number is: " + firstNumber / secondNumber);
    }
}

This program reads two numbers as inputs from the user and print the result of dividing the first number by the second number.

This program will work fine if the user enters any valid value. For example:

Enter a number: 
10
Enter another number: 
2
The result of first-number/second-number is: 5

But if the second number is 0, it will throw an ArithmeticException:

Enter a number: 
10
Enter another number: 
0
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at com.company.Main.main(Main.java:15)

We can use a try-catch block to handle these type of exceptions.

try {
    System.out.println("The result of first-number/second-number is: " + firstNumber / secondNumber);
}catch(ArithmeticException e){
    System.out.println("Please enter valid inputs!!");
}

You might also like: