1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Try Catch Blocks
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
01Hrs
21Mins
55Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Try Catch Blocks

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
01Hrs
21Mins
55Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Try-Catch

Overview

Exception Handling is one of the most critical real-world skills in Java development. An Exception is an unexpected event that disrupts the normal flow of a program — for example, reading a file that doesn't exist, dividing a number by zero, or receiving a null value where an object was expected.

In Java, exceptions are objects. Every exception inherits from the root Throwable class, which splits into two major branches: Errors (catastrophic JVM-level problems like OutOfMemoryError that you generally cannot recover from) and Exceptions (recoverable application-level problems). Exceptions are further split into Checked Exceptions (like IOException, which the compiler forces you to handle) and Unchecked/Runtime Exceptions (like NullPointerException, which the compiler doesn't force you to handle but which crash the program at runtime).

The try-catch-finally block is your safety net. Code inside the try block is executed normally. If any line inside it throws an exception, the JVM immediately jumps down to the matching catch block to handle it gracefully. The optional finally block always executes regardless of whether an exception occurred — it is designed for cleanup code like closing file streams or releasing database connections.

Syntax

The finally block is critical for resource cleanup. Whether the file was found or not, the cleanup code must always execute to prevent resource leaks.

Basic Exception Handling
java
import java.io.FileReader;
import java.io.IOException;

public class Main {
    public static void main(String[] args) {
        // 1. Catching a Specific Exception
        try {
            int[] numbers = {1, 2, 3};
            System.out.println(numbers[10]); // ArrayIndexOutOfBoundsException
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Caught: " + e.getMessage());
        }

        // 2. Multi-Catch Block (Java 7+)
        try {
            String s = null;
            s.length(); // NullPointerException
        } catch (NullPointerException | IllegalArgumentException e) {
            System.out.println("Caught multi: " + e.getClass().getSimpleName());
        }

        // 3. The Finally Block — Always runs!
        FileReader file = null;
        try {
            file = new FileReader("config.txt");
            // ... read the file
        } catch (IOException e) {
            System.out.println("File not found!");
        } finally {
            // Cleanup: runs even if an exception occurred
            System.out.println("Cleaning up resources...");
        }
    }
}

Common Pitfalls

  • Silently swallowing exceptions with empty catch blocks. Writing catch (Exception e) { } is one of the most dangerous anti-patterns in Java. If your code crashes and you swallowed the exception, you have zero visibility into why. Always at minimum log the error with e.printStackTrace() or a proper logger.
  • Catching the root Exception or Throwable class too broadly. Writing catch (Exception e) will intercept almost every exception in the program, including ones you never intended to catch. Always catch the most specific exception type possible.
  • Using try-catch for control flow logic. Exception handling has significant performance overhead compared to a simple if statement. Do not write try { Integer.parseInt(str); } catch(...) {} to check if a string is a number. Use str.matches("\\d+") instead.

Interview Questions

What is the difference between a Checked Exception and an Unchecked Exception?

A Checked Exception (like IOException, SQLException) is verified by the compiler. You MUST either handle it with a try-catch or declare it on the method signature with throws. An Unchecked Exception (like NullPointerException, ArrayIndexOutOfBoundsException) is a subclass of RuntimeException. The compiler does not force you to handle it, but it will crash the program at runtime if unhandled.

Is there any situation where the finally block does NOT execute?

Yes, two rare cases. First, if System.exit() is called anywhere inside the try or catch blocks, the JVM immediately shuts down and the finally block is skipped. Second, if a fatal Error like OutOfMemoryError occurs and the JVM itself crashes, the finally block won't run.

What is try-with-resources (Java 7+) and why is it superior to a finally block for I/O?

Try-with-resources (try (FileReader f = new FileReader(path)) {}) automatically calls .close() on the resource when the block exits, whether by success or exception. It eliminates the boilerplate finally block and also properly handles the edge case where both the main code and the finally cleanup code throw exceptions simultaneously.

Real-World Example

In a production REST API (Spring Boot), every external network call — reading from a database, calling a payment gateway, parsing user JSON — must be wrapped in try-catch. Without this, a single bad request would crash the entire thread pool and take down the whole server for all users.

example
java
@RestController
public class UserController {
    @GetMapping("/user/{id}")
    public ResponseEntity<User> getUser(@PathVariable int id) {
        try {
            User user = db.findById(id); // Could throw SQLException
            return ResponseEntity.ok(user);
        } catch (UserNotFoundException e) {
            return ResponseEntity.status(404).body(null);
        } catch (SQLException e) {
            log.error("DB error for user " + id, e);
            return ResponseEntity.status(500).body(null);
        }
    }
}

Check Your Knowledge

Test your understanding of Try-Catch with these quick questions.

Question 1

Which block in a try-catch-finally construct is guaranteed to always execute?

Question 2

What is the correct order for the try-catch-finally structure?

Question 3

A Checked Exception must be handled at compile time. Which of the following is a Checked Exception?

Take Java Quiz
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Try-Catch

Overview

Exception Handling is one of the most critical real-world skills in Java development. An Exception is an unexpected event that disrupts the normal flow of a program — for example, reading a file that doesn't exist, dividing a number by zero, or receiving a null value where an object was expected.

In Java, exceptions are objects. Every exception inherits from the root Throwable class, which splits into two major branches: Errors (catastrophic JVM-level problems like OutOfMemoryError that you generally cannot recover from) and Exceptions (recoverable application-level problems). Exceptions are further split into Checked Exceptions (like IOException, which the compiler forces you to handle) and Unchecked/Runtime Exceptions (like NullPointerException, which the compiler doesn't force you to handle but which crash the program at runtime).

The try-catch-finally block is your safety net. Code inside the try block is executed normally. If any line inside it throws an exception, the JVM immediately jumps down to the matching catch block to handle it gracefully. The optional finally block always executes regardless of whether an exception occurred — it is designed for cleanup code like closing file streams or releasing database connections.

Syntax

The finally block is critical for resource cleanup. Whether the file was found or not, the cleanup code must always execute to prevent resource leaks.

Basic Exception Handling
java
import java.io.FileReader;
import java.io.IOException;

public class Main {
    public static void main(String[] args) {
        // 1. Catching a Specific Exception
        try {
            int[] numbers = {1, 2, 3};
            System.out.println(numbers[10]); // ArrayIndexOutOfBoundsException
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Caught: " + e.getMessage());
        }

        // 2. Multi-Catch Block (Java 7+)
        try {
            String s = null;
            s.length(); // NullPointerException
        } catch (NullPointerException | IllegalArgumentException e) {
            System.out.println("Caught multi: " + e.getClass().getSimpleName());
        }

        // 3. The Finally Block — Always runs!
        FileReader file = null;
        try {
            file = new FileReader("config.txt");
            // ... read the file
        } catch (IOException e) {
            System.out.println("File not found!");
        } finally {
            // Cleanup: runs even if an exception occurred
            System.out.println("Cleaning up resources...");
        }
    }
}

Common Pitfalls

  • Silently swallowing exceptions with empty catch blocks. Writing catch (Exception e) { } is one of the most dangerous anti-patterns in Java. If your code crashes and you swallowed the exception, you have zero visibility into why. Always at minimum log the error with e.printStackTrace() or a proper logger.
  • Catching the root Exception or Throwable class too broadly. Writing catch (Exception e) will intercept almost every exception in the program, including ones you never intended to catch. Always catch the most specific exception type possible.
  • Using try-catch for control flow logic. Exception handling has significant performance overhead compared to a simple if statement. Do not write try { Integer.parseInt(str); } catch(...) {} to check if a string is a number. Use str.matches("\\d+") instead.

Interview Questions

What is the difference between a Checked Exception and an Unchecked Exception?

A Checked Exception (like IOException, SQLException) is verified by the compiler. You MUST either handle it with a try-catch or declare it on the method signature with throws. An Unchecked Exception (like NullPointerException, ArrayIndexOutOfBoundsException) is a subclass of RuntimeException. The compiler does not force you to handle it, but it will crash the program at runtime if unhandled.

Is there any situation where the finally block does NOT execute?

Yes, two rare cases. First, if System.exit() is called anywhere inside the try or catch blocks, the JVM immediately shuts down and the finally block is skipped. Second, if a fatal Error like OutOfMemoryError occurs and the JVM itself crashes, the finally block won't run.

What is try-with-resources (Java 7+) and why is it superior to a finally block for I/O?

Try-with-resources (try (FileReader f = new FileReader(path)) {}) automatically calls .close() on the resource when the block exits, whether by success or exception. It eliminates the boilerplate finally block and also properly handles the edge case where both the main code and the finally cleanup code throw exceptions simultaneously.

Real-World Example

In a production REST API (Spring Boot), every external network call — reading from a database, calling a payment gateway, parsing user JSON — must be wrapped in try-catch. Without this, a single bad request would crash the entire thread pool and take down the whole server for all users.

example
java
@RestController
public class UserController {
    @GetMapping("/user/{id}")
    public ResponseEntity<User> getUser(@PathVariable int id) {
        try {
            User user = db.findById(id); // Could throw SQLException
            return ResponseEntity.ok(user);
        } catch (UserNotFoundException e) {
            return ResponseEntity.status(404).body(null);
        } catch (SQLException e) {
            log.error("DB error for user " + id, e);
            return ResponseEntity.status(500).body(null);
        }
    }
}

Check Your Knowledge

Test your understanding of Try-Catch with these quick questions.

Question 1

Which block in a try-catch-finally construct is guaranteed to always execute?

Question 2

What is the correct order for the try-catch-finally structure?

Question 3

A Checked Exception must be handled at compile time. Which of the following is a Checked Exception?

Take Java Quiz

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A