Java > Core Java > Exception Handling > Checked vs Unchecked Exceptions
Checked vs. Unchecked Exceptions in Java
This example demonstrates the difference between checked and unchecked exceptions in Java. Checked exceptions must be caught or declared to be thrown, while unchecked exceptions are not enforced by the compiler.
Checked Exception Example: IOException
This code tries to read from a file that might not exist. FileReader
and BufferedReader
throw IOException
, which is a checked exception. The compiler forces us to either catch this exception using a try-catch
block or declare that the main
method throws it using throws IOException
. If we remove the try-catch
block, the code will not compile.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class CheckedExceptionExample {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader("nonexistent_file.txt"));
String line = br.readLine();
while (line != null) {
System.out.println(line);
line = br.readLine();
}
br.close();
} catch (IOException e) {
System.err.println("An IOException occurred: " + e.getMessage());
}
}
}
Unchecked Exception Example: NullPointerException
This code attempts to call the length()
method on a null
String, which results in a NullPointerException
. NullPointerException
is an unchecked exception, which means the compiler does not require us to handle it. Although we've included a try-catch block here, it's not strictly necessary for the code to compile. The program will compile and potentially throw the exception at runtime if the try-catch
is not present.
public class UncheckedExceptionExample {
public static void main(String[] args) {
String str = null;
try {
System.out.println(str.length()); // This will throw a NullPointerException
} catch (NullPointerException e) {
System.err.println("A NullPointerException occurred: " + e.getMessage());
}
System.out.println("Program continues after potential exception.");
}
}
Concepts Behind the Snippet
Checked exceptions are exceptions that the compiler forces you to handle or declare in the method signature. Unchecked exceptions are not checked at compile time and usually result from programming errors.
Real-Life Use Case
IllegalArgumentException
) or unexpected null values (resulting in a NullPointerException
).
Best Practices
Exception
unless you really need to handle all possible exceptions. Catch more specific exceptions instead.
Interview Tip
Be prepared to explain the difference between checked and unchecked exceptions, give examples of each, and discuss when to use each type. Also, be familiar with common exception types like IOException
, NullPointerException
, IllegalArgumentException
, and IndexOutOfBoundsException
.
When to Use Them
Alternatives
null
or an error code). However, this can lead to less explicit error handling.
Pros and Cons
Checked Exceptions:
Unchecked Exceptions:
FAQ
-
What is the difference between Error and Exception?
Errors are typically unrecoverable problems that a program cannot handle (e.g.,OutOfMemoryError
). Exceptions are conditions that a program can potentially catch and recover from. -
What are some common checked exceptions?
Common checked exceptions includeIOException
,SQLException
, andClassNotFoundException
. -
What are some common unchecked exceptions?
Common unchecked exceptions includeNullPointerException
,IllegalArgumentException
,IndexOutOfBoundsException
, andArithmeticException
. -
Should I catch every exception?
No. You should only catch exceptions that you can reasonably handle. Catching and ignoring exceptions can mask underlying problems and make debugging difficult.