DEV Community

Hayes vincent
Hayes vincent

Posted on

Compile-Time Exception (Checked Exception)and Runtime Exception (Unchecked Exception)

*1. Compile-Time Exception (Checked Exception)
*

These are errors that are checked before the program runs (during compilation).

✔ Key Points:
Detected by the compiler
Must be handled using try-catch or throws
If not handled → program will NOT compile

Examples:
File not found
IOException
SQLException
 Example Code:

import java.io.*;

public class Test {
    public static void main(String[] args) throws IOException {
        FileReader file = new FileReader("abc.txt"); // may not exist
    }
}
Enter fullscreen mode Exit fullscreen mode

If you don’t handle it → compile-time error

** 2. Runtime Exception (Unchecked Exception)**

These occur while the program is running.

Key Points:
NOT checked at compile time
Occur due to logic errors
Program compiles successfully but crashes during execution

Examples:
ArithmeticException (divide by zero)
NullPointerException
ArrayIndexOutOfBoundsException
 Example Code:
public class Test {
    public static void main(String[] args) {
        int a = 10 / 0; // runtime error
    }
}


Enter fullscreen mode Exit fullscreen mode

Compiles fine, but crashes when running

Main Differences

Feature Compile-Time Exception Runtime Exception
Checked by Compiler JVM (during execution)
Handling required Yes (mandatory) No (optional)
When occurs Before running During running
Cause External issues (file, DB) Logic mistakes
Example IOException NullPointerException

Top comments (0)