11.5 Checked and Unchecked Exceptions
Java’s predefined exceptions are divided into two categories: checked exceptions and unchecked exceptions.
Checked exception
Any exception that the compiler can recognize is called a checked exception. These are the exceptions that you should handle in your program. If the code in a method can throw a checked exception, then that method must meet one of the following requirements:
- It must handle the exception, or
- It must have a throws clause listed in the method header.
Consider a program that reads two integers from a file named sample.txt. Since IOException is a checked exception either it should be handled using catch block or by using throws
Program using throws
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class ReadNum
{
public static void main(String[] args) throws IOException
{
try (Scanner inFile = new Scanner(new FileReader("sample.txt")))
{
int num1 = inFile.nextInt();
int num2 = inFile.nextInt();
int sum = num1 + num2;
System.out.println("sum " + sum);
}
}
}
Program Using try/catch Block
import java.io.FileReader;
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.Scanner;
public class ReadNum
{
public static void main(String[] args)
{
try (Scanner inFile = new Scanner(new FileReader("sample.txt")))
{
int num1 = inFile.nextInt();
int num2 = inFile.nextInt();
int sum = num1 + num2;
System.out.println("sum " + sum);
}
catch (IOException | InputMismatchException ex)
{
System.out.println(ex.toString());
}
}
}
Unchecked Exception
An unchecked exception is A SUBCLASS of RuntimeException (as well as RuntimeException itself). These exceptions are mostly caused by programmers writing incorrect code. Most of the built-in exceptions (e.g., ArithmeticException, IndexOutOfBoundsException) are unchecked.
Unchecked exceptions can be caught in a try block, but if not, they need not be listed in the function's throws clause.
+-----------+ | Throwable | +-----------+ / \ / \ +-------+ +-----------+ | Error | | Exception | +-------+ +-----------+ / | \ / | \ \________/ \______/ \ +------------------+ unchecked checked | RuntimeException | +------------------+ / | | \ \_________________/ unchecked