Java Concepts I’m Mastering – Part 11: Exception Handling (try-catch-finally)
Continuing my journey of mastering Java fundamentals.
Today’s concept: Exception Handling — because real programs must handle errors gracefully.
What is an Exception?
An exception is:
An unexpected event that disrupts normal program flow.
Examples:
Dividing by zero
Accessing invalid array index
Reading a missing file
If not handled → program crashes.
try-catch Block
We use try to write risky code
and catch to handle errors.
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
}
Instead of crashing, it prints a message.
finally Block
The finally block:
Always executes
Used for cleanup (closing files, DB connections, etc.)
try {
System.out.println("Trying...");
} catch (Exception e) {
System.out.println("Error occurred");
} finally {
System.out.println("This always runs");
}
Types of Exceptions
Checked Exceptions (compile-time)
Must be handled
Example: IOException
Unchecked Exceptions (runtime)
Occur during execution
Example: NullPointerException
Why It’s Important
Prevents program crashes
Improves reliability
Makes applications production-ready
Good developers don’t just write logic —
they handle failure properly.
What I Learned
Always handle predictable errors
Use specific exceptions instead of generic ones
Clean up resources using finally
Exception handling separates beginners from professionals.
Next in the series: Collections Framework in Java (ArrayList vs LinkedList)
Top comments (0)