Java try-catch-finally Quiz | 25 Tricky Coding MCQs

Yogi Siddeswara 0
STUDYECRAT Java : try-catch-finally
60s
Java Try-Catch-Finally

Prove your skills in this interactive quiz

💻

Live Code

Run snippets directly

⏱️

Timed

60s per question

🏆

Scored

Earn 3D badges

Java Exception Handling : try-catch-finally: Key Interview Points

1. Finally Block Always Executes

try {
  System.out.println("Try block");
  throw new RuntimeException();
} catch (Exception e) {
  System.out.println("Catch block");
} finally {
  System.out.println("Finally block");
}
// Output: Try → Catch → Finally (even with exception)
  • Tip: Use finally for cleanup (e.g., closing files/DB connections)
  • Real Use: Database connection cleanup in Spring applications

2. Return Statement in Finally Overrides Try/Catch

String demo() {
  try {
    return "From try";
  } finally {
    return "From finally";
  }
}
// Method returns "From finally" (overrides try's return)
  • Tip: Avoid returns in finally - it masks original exceptions
  • Real Use: Common bug in legacy transaction handling code

3. System.exit() Skips Finally Block

try {
  System.exit(0);
} finally {
  System.out.println("This never executes");
}
// JVM terminates before finally runs
  • Tip: Use shutdown hooks for mandatory cleanup with System.exit()
  • Real Use: Critical in batch jobs where resources must be released

4. Nested Try-Catch Execution Flow

try {
  try {
    throw new IOException();
  } catch (SQLException e) {
    System.out.println("Inner catch");
  }
} catch (Exception e) {
  System.out.println("Outer catch");
}
// Output: "Outer catch" (exception bubbles up)
  • Tip: Order catch blocks from most specific to most general
  • Real Use: Handling API failures with retry mechanisms

5. Try-With-Resources vs Finally

try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
  System.out.println(br.readLine());
} catch (IOException e) {
  System.out.println("Auto-closed even if exception occurs");
}
// Resource implements AutoCloseable (Java 7+)
  • Tip: Prefer try-with-resources over manual finally cleanup
  • Real Use: File/network stream handling in modern Java

💡 Pro Interview Tip

When asked about exception handling, always mention the "throw early, catch late" principle - validate inputs immediately but handle exceptions at the appropriate layer (e.g., UI vs service layer).


Java Data Types Quiz: 25 MCQs with Answers (Interview Prep)

Post a Comment

0 Comments