0% found this document useful (0 votes)
2 views21 pages

Exception Handling in Java

Exception handling in Java is a mechanism to manage runtime errors, allowing the program to continue its normal flow despite disruptions. It involves using try-catch blocks to catch exceptions and a finally block to execute code regardless of whether an exception occurred. Additionally, the 'throw' keyword is used to explicitly throw exceptions, while 'throws' is used to declare exceptions that a method may throw.

Uploaded by

paulpradipta2003
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views21 pages

Exception Handling in Java

Exception handling in Java is a mechanism to manage runtime errors, allowing the program to continue its normal flow despite disruptions. It involves using try-catch blocks to catch exceptions and a finally block to execute code regardless of whether an exception occurred. Additionally, the 'throw' keyword is used to explicitly throw exceptions, while 'throws' is used to declare exceptions that a method may throw.

Uploaded by

paulpradipta2003
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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.

You might also like