-4

Why arithmeticexception is unchecked exception and why we define 2 types of exception Unchecked and Checked in Java?

Cœur
  • 37,241
  • 25
  • 195
  • 267

1 Answers1

1

Checked exceptions are the exceptions that are checked at compile time. If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using throws keyword.

import java.io.*;

class Main {
    public static void main(String[] args) {
        FileReader file = new FileReader("C:\\test\\a.txt");
        BufferedReader fileInput = new BufferedReader(file);

        // Print first 3 lines of file "C:\test\a.txt"
        for (int counter = 0; counter < 3; counter++) 
            System.out.println(fileInput.readLine());

        fileInput.close();
    }
}

Unchecked are the exceptions that are not checked at compiled time. In C++, all exceptions are unchecked, so it is not forced by the compiler to either handle or specify the exception. It is up to the programmers to be civilized, and specify or catch the exceptions.

                 +-----------+
                 | Throwable |
                 +-----------+
                  /         \
                 /           \
          +-------+          +-----------+
          | Error |          | Exception |
          +-------+          +-----------+
           /  |  \            / |        \
         \_________/        \____/        \
                                     +------------------+
           unchecked       checked   | RuntimeException |
                                     +------------------+
                                      /   |    |   |  \
                                     \_________________/

                                         unchecked
Xavi López
  • 27,550
  • 11
  • 97
  • 161