STUDYECRAT Java :Checked vs Unchecked Exceptions
60s
Java Checked vs Unchecked Exceptions
Prove your skills in this interactive quiz
Live Code
Run snippets directly
Timed
60s per question
Scored
Earn 3D badges
★ Checked vs Unchecked Exceptions: Key Interview Points
1. Compiler-Enforced vs Runtime Exceptions
// Checked Exception (Must be handled)
try {
FileReader file = new FileReader("test.txt");
} catch (FileNotFoundException e) {
System.out.println("File not found!");
}
// Unchecked Exception (No compiler enforcement)
int[] nums = {1, 2}; System.out.println(nums[3]); // Throws ArrayIndexOutOfBoundsException
// Unchecked Exception (No compiler enforcement)
int[] nums = {1, 2}; System.out.println(nums[3]); // Throws ArrayIndexOutOfBoundsException
- Tip: Use
RuntimeException
for programming errors, checked exceptions for recoverable conditions - Real Use: File I/O operations always throw checked exceptions to force error handling
2. Unchecked Exception Propagation
void methodA() {
methodB(); // No try-catch needed
}
void methodB() {
throw new NullPointerException(); // Unchecked
}
// Checked exceptions must be declared in throws clause
void readFile() throws IOException { Files.readAllLines(Paths.get("data.txt")); }
// Checked exceptions must be declared in throws clause
void readFile() throws IOException { Files.readAllLines(Paths.get("data.txt")); }
- Tip: Unchecked exceptions bubble up automatically; checked exceptions break compilation if unhandled
- Real Use: Spring Framework prefers unchecked exceptions for transaction rollbacks
3. Creating Domain-Specific Exceptions
// Checked custom exception
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}
// Unchecked custom exception
class InvalidUserInputException extends RuntimeException { InvalidUserInputException(String error) { super("Invalid input: " + error); } }
// Unchecked custom exception
class InvalidUserInputException extends RuntimeException { InvalidUserInputException(String error) { super("Invalid input: " + error); } }
- Tip: Extend
RuntimeException
if clients shouldn't be forced to handle it - Real Use: Banking apps use checked exceptions for business rule violations
4. Automatic Resource Management
// Pre-Java 7 (Manual cleanup)
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("file.txt"));
System.out.println(br.readLine());
} finally {
if (br != null) br.close(); // Forced cleanup
}
// Java 7+ (AutoCloseable)
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) { System.out.println(br.readLine()); } // Auto-closed
// Java 7+ (AutoCloseable)
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) { System.out.println(br.readLine()); } // Auto-closed
- Tip: Resources must implement
AutoCloseable
to work with try-with-resources - Real Use: Database connections and file streams benefit from automatic closure
5. Common Pitfalls to Avoid
// 1. Swallowing exceptions
try {
riskyOperation();
} catch (Exception e) {
e.printStackTrace(); // Bad practice!
}
// 2. Catching Throwable
try { // Code } catch (Throwable t) { // Catches Errors too! // Avoid unless absolutely necessary }
// 2. Catching Throwable
try { // Code } catch (Throwable t) { // Catches Errors too! // Avoid unless absolutely necessary }
- Tip: Always log exceptions with context using
logger.error("Context", e)
- Real Use: Production systems fail fast when catching
Error
is avoided
💡 Pro Interview Tip
When asked about exception handling, distinguish between checked exceptions (compile-time enforcement for recoverable errors) and unchecked exceptions (runtime failures indicating bugs). Mention real-world tradeoffs - checked exceptions can clutter code but ensure error handling, while unchecked exceptions follow the "fail fast" principle.