DEV Community

Arun Kumar
Arun Kumar

Posted on

Compile-Time and Runtime Exceptions

In Java, exceptions are mainly divided into two types:

Compile-Time Exceptions (Checked Exceptions)
Runtime Exceptions (Unchecked Exceptions)

What is a Compile-Time Exception?

A Compile-Time Exception (also called a Checked Exception) is an error that is detected during compilation.
The compiler checks these exceptions before the program runs.

Examples:

  • IOException
  • SQLException
  • FileNotFoundException
Example Program:
import java.io.*;

class Test {
    public static void main(String[] args) {
        FileReader file = new FileReader("test.txt"); // Compile-time error
    }
}
Enter fullscreen mode Exit fullscreen mode
Correct Way:
import java.io.*;

class Test {
    public static void main(String[] args) {
        try {
            FileReader file = new FileReader("test.txt");
        } catch (FileNotFoundException e) {
            System.out.println("File not found");
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

What is a Runtime Exception?

A Runtime Exception (also called an Unchecked Exception) occurs while the program is running.

Examples:

  • ArithmeticException
  • NullPointerException
  • ArrayIndexOutOfBoundsException
Example Program:
class Test {
    public static void main(String[] args) {
        int a = 10;
        int b = 0;
        int result = a / b; // Runtime error
        System.out.println(result);
    }
}
Enter fullscreen mode Exit fullscreen mode
Handling Runtime Exception:
class Test {
    public static void main(String[] args) {
        try {
            int a = 10;
            int b = 0;
            int result = a / b;
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)