try-catch-finally
In Java, an exception is an unexpected event that interrupts the normal flow of your program.
Examples:
Dividing by zero.
Accessing an invalid array index.
Trying to open a file that doesnโt exist.
If you donโt handle exceptions properly, your program crashes.
Java uses a built-in exception handling system that lets you:
Detect problems.
Catch them.
Handle them gracefully without killing the whole program.
To handle exceptions, you wrap risky code in a try block.
If something goes wrong, Java jumps to the catch block.
Example:
How this works:
try
contains code that might fail.
If 10 / 0
happens, an ArithmeticException
is thrown.
The catch
block catches it and prints a safe message.
Sometimes, you need code that always runs, whether an exception happens or not.
This is what finally
is for โ it runs no matter what.
Example:
Key points:
If the try
works: the finally
runs.
If the catch
runs: the finally
still runs.
Good for closing files, releasing resources, or logging.