Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

What is the difference between checked and unchecked exceptions in Java? Java में checked और unchecked exceptions में क्या अंतर है?

Answer
TypeChecked atMust be declared/caught?Examples
Checked exceptionCompile timeYes - or method must declare 'throws'IOException, SQLException
Unchecked exceptionRuntime onlyNo - compiler doesn't enforce handlingNullPointerException, 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 करना ज़रूरी?उदाहरण
CheckedCompile 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?