Exception handling is an important concept in Java that helps us handle errors smoothly without crashing the program.
In this blog, we will clearly understand:
What is Compile-Time Exception
What is Runtime Exception
Key Differences with examples
What is an Exception?
An exception is an error that occurs during the execution of a program.
It interrupts the normal flow of the program.
1. Compile-Time Exception (Checked Exception)
Definition
Compile-time exceptions are errors that are checked by the compiler before the program runs.
If not handled, the program will not compile.
Examples
- IOException
- SQLException
- FileNotFoundException
Example Code (Java)
import java.io.*;
class Main {
public static void main(String[] args) throws IOException {
FileReader file = new FileReader("test.txt"); // may throw exception
BufferedReader br = new BufferedReader(file);
System.out.println(br.readLine());
}
}
If we don’t use throws or try-catch, compilation will fail.
Key Points
✔ Checked at compile time
✔ Must be handled using try-catch or throws
✔ Safer, because errors are caught early
2. Runtime Exception (Unchecked Exception)
Definition
Runtime exceptions occur during program execution.
Compiler does NOT check these errors.
Examples
- ArithmeticException
- NullPointerException
- ArrayIndexOutOfBoundsException
Example Code (Java)
class Main {
public static void main(String[] args) {
int a = 10 / 0; // runtime error
System.out.println(a);
}
}
This code compiles successfully, but crashes at runtime.
Key Points
✔ Occurs at runtime
✔ Not checked by compiler
✔ Optional to handle
Difference Table
| Feature | Compile-Time Exception | Runtime Exception |
|---|---|---|
| Checked by | Compiler | JVM at runtime |
| Handling | Mandatory | Optional |
| Occurs | Before execution | During execution |
| Examples | IOException, SQLException | NullPointerException, ArithmeticException |
| Program Status | Won’t compile | Compiles but crashes |
Real-Life Example
Compile-Time Exception
Like missing documents before an exam → You cannot enter
Runtime Exception
Like bike breakdown during travel → Problem happens suddenly
Advantages of Exception Handling
✔ Prevents program crash
✔ Maintains normal flow
✔ Helps debugging
✔ Improves code quality
Important Note
All compile-time exceptions are checked exceptions
All runtime exceptions are unchecked exceptions
Conclusion
Understanding the difference between compile-time and runtime exceptions is very important for writing robust Java programs.
Compile-time exceptions = handled early
Runtime exceptions = handled during execution
Top comments (0)