The exception handling mechanism via try-catch-finally has been part of Java since the beginning of the language's development. The main purpose is to provide structured error management, separating operational code from error-handling code.
Problem: any non-standard or erroneous behavior leads to the throw of an exception. Without try-catch, it can only be propagated further up the call stack. With this approach, the program can terminate abnormally.
Solution — the use of try { } catch { } finally { }, which allows handling expected exceptions and ensuring that final actions are executed (resource deallocation, file closure, transaction rollback).
Code Example:
try { FileInputStream fin = new FileInputStream("test.txt"); int data = fin.read(); } catch (IOException e) { System.out.println("File operation error: " + e.getMessage()); } finally { fin.close(); }
Key Features:
try block contains potentially erroneous codecatch block intercepts and handles exceptionsfinally block always executes, even on return/exceptionCan finally not be executed?
Yes, if there is a System.exit() call inside the block, the process terminates abnormally, or the JVM physically "crashes".
Can you use try-catch without finally?
Yes, the finally block is not mandatory. However, if resource cleanup is required, it is typically used. Since Java 7, there is try-with-resources.
What happens if there is an exception in finally?
If a new error occurs in finally, it "overwrites" the original one (if it is not caught separately), which can mask problems.
try { throw new RuntimeException("fail in try"); } finally { throw new RuntimeException("fail in finally"); } // The resulting stacktrace — only "fail in finally"
catch(Exception e) {} empty)throw e; without new Exception(e))In a project, the finally block contained code that could itself throw IOException. When an error occurred in try, the original exception was completely lost, making error diagnosis very difficult.
Pros:
Cons:
Instead of finally, the team switched to try-with-resources. Each resource implements AutoCloseable, deallocation happens automatically, and exceptions are logged separately as errors.
Pros:
Cons: