Java.Core.How does Java handle exceptions with try-catch-finally?

🌪️ What is try-catch-finally?

This is Java’s exception handling mechanism to catch errors that happen during runtime and gracefully recover (instead of crashing the program).

  • try — Code that might throw an exception.
  • catch — Code that handles the exception.
  • finally — Code that always runs, whether an exception occurred or not (cleanup logic like closing files or connections).

📜 Basic Structure

try {
    // Risky code (could throw an exception)
} catch (ExceptionType e) {
    // Handle the exception
} finally {
    // Cleanup code (always runs, even if exception is thrown)
}

✅ Example — Division Handling

public class ExceptionExample {
    public static void main(String[] args) {
        try {
            int result = divide(10, 0);
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero: " + e.getMessage());
        } finally {
            System.out.println("This always runs (cleanup)");
        }
    }

    static int divide(int a, int b) {
        return a / b;
    }
}
Cannot divide by zero: / by zero
This always runs (cleanup)

⚙️ Flow Explanation

StepWhat happens?
Enter try blockRisky code runs
Exception thrown?Yes — Jump to catch
catch block runsHandles the exception
finally block runsRuns always (whether exception or not)

🔗 Important Rules

CaseWhat Happens?
No exceptiontry runs fully, finally runs, catch skipped
Exception throwntry stops, jumps to matching catch, then finally runs
Exception thrown but not caughtfinally still runs before propagating exception up
Exception inside finallyThat new exception can replace the original one

🎯 Key Properties of finally

  • Guaranteed execution (unless JVM exits via System.exit() or crash).
  • Used for closing resources, releasing locks, etc.
  • In modern Java (Java 7+), you often use try-with-resources instead (more on that later).

🔥 Example — Multiple Catch Blocks

try {
    int[] nums = {1, 2};
    System.out.println(nums[5]);  // ArrayIndexOutOfBoundsException
} catch (ArithmeticException e) {
    System.out.println("Math error");
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Array index error");  // This block will catch
} finally {
    System.out.println("Always cleanup");
}

Output

Array index error
Always cleanup

🔄 Modern Alternative — Try-with-Resources (Java 7+)

For resources like files or sockets, instead of:

FileInputStream fis = null;
try {
    fis = new FileInputStream("file.txt");
    // read file
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (fis != null) {
        fis.close();
    }
}
try (FileInputStream fis = new FileInputStream("file.txt")) {
    // read file
} catch (IOException e) {
    e.printStackTrace();
}
  • No finally needed — resource closes automatically.

⚠️ What happens if finally has a return?

This is a tricky case and a popular interview question.

public int riskyMethod() {
    try {
        return 1;
    } finally {
        return 2;  // This overrides the try return!
    }
}

✅ Output: It always returns 2finally overrides any return from try or catch.

🔥 Quick Recap

BlockPurposeRuns When?
tryRisky codeAlways
catchHandle exceptionIf exception happens
finallyCleanup (closing files, releasing locks)Always (even if no exception)

📚 Summary

try-catch-finally is Java’s main exception handling tool.
finally is great for cleanup, but try-with-resources is often better for resources.
finally almost always runs — except for extreme cases like System.exit().
✅ Multiple catch blocks allow handling different exceptions differently.
✅ A finally block can override a return (but that’s bad practice).

This entry was posted in Без рубрики. Bookmark the permalink.