Exception Handling
Java
What is Exception Handling?
Exception :- an abnormal condition that occurs at runtime and disrupts the
normal flow of the program.
Q.) What happens if we divide by zero ?
Q.) What if file is not present ?
Exception handling is a mechanism to handle runtime errors,
allowing the normal flow of a program to continue.
Exceptions are events that occur during program execution
that disrupt the normal flow of instructions.
Basic try-catch Example
•The try block contains code that might throw an exception,
•The catch block handles the exception if it occurs.
Finally Block
The finally block always executed whether an exception is thrown or not.
The finally is used for closing resources like db connections, open files and
network connections, It is used after a try-catch block to execute code that must
run.
throw and throws
1. Throw : Used to explicitly throw a single exception. We use throw when something goes
wrong (or “shouldn’t happen”) and we want to stop normal flow and hand control to
exception handling.
2. Throws : Declares exceptions that a method might throw,
informing the caller to handle them. It is mainly used with checked
exceptions (explained below). If a method calls another method
that throws a checked exception, and it doesn’t catch it, it must
declare that exception in its throws clause
Nested try-catch
In Java, you can place one try-catch block inside another to handle exceptions
at multiple levels.