Interview question
What is the difference between checked and unchecked exceptions in Java? Java में checked और unchecked exceptions में क्या अंतर है?
Answer
| Type | Checked at | Must be declared/caught? | Examples |
|---|---|---|---|
| Checked exception | Compile time | Yes - or method must declare 'throws' | IOException, SQLException |
| Unchecked exception | Runtime only | No - compiler doesn't enforce handling | NullPointerException, ArithmeticException |
import java.io.*;
// Checked exception - compiler FORCES you to handle or declare it
public void readFile() throws IOException { // must declare
FileReader file = new FileReader('data.txt');
}
// Or handle it directly
public void readFileSafe() {
try {
FileReader file = new FileReader('data.txt');
} catch (IOException e) {
System.out.println('File error: ' + e.getMessage());
}
}
// Unchecked exception - compiler does NOT force handling
public void divide(int a, int b) {
int result = a / b; // no try-catch or throws required
}
// If b is 0, throws ArithmeticException at RUNTIME, not caught at compile time
// Class hierarchy:
// Throwable
// -> Exception (checked, unless it extends RuntimeException)
// -> RuntimeException (unchecked)
// -> Error (unchecked, serious JVM-level problems, e.g. OutOfMemoryError)| Type | कब check होता है | Handle करना ज़रूरी? | उदाहरण |
|---|---|---|---|
| Checked | Compile time | हाँ | IOException, SQLException |
| Unchecked | सिर्फ Runtime | नहीं | NullPointerException |
import java.io.*;
public void readFile() throws IOException {
FileReader file = new FileReader('data.txt');
}
public void readFileSafe() {
try {
FileReader file = new FileReader('data.txt');
} catch (IOException e) {
System.out.println('File error: ' + e.getMessage());
}
}
public void divide(int a, int b) {
int result = a / b; // try-catch ज़रूरी नहीं
}
// b शून्य हो तो RUNTIME पर ArithmeticException
// Class hierarchy:
// Throwable -> Exception (checked) -> RuntimeException (unchecked)
// -> Error (unchecked, serious JVM problems)Was this answer clear?