ExceptionHandling 1
ExceptionHandling 1
1
Contents
Introduction
Exception- Class Hierarchy.
Types of Exception
Exception Handling in Java
Difference between throw and throws
Difference between final, finally and finalize
2
Introduction
An exception can occur for many different reasons, including the following:
3
Any exception which is thrown, must be caught by an exception handler.
4
Exception -Class Hierarchy
5
Errors are problems that mainly occur due to the
lack of system resources. It cannot be caught or
handled. It indicates a serious problem. It occurs
at run time. These are always unchecked. An
example of errors is OutOfMemoryError,,, etc.
are the subclasses of the Error class.
6
Types of Exception
7
Unchecked exceptions: An Unchecked exception is an exception that occurs
at the time of execution, these are also called as Runtime Exceptions. The
classes that inherit the RuntimeException are known as
unchecked exceptions
For example, if you have declared an array of size 5 in your program, and
trying to call the 6th element of the array then an ArrayIndexOutOfBounds
Exception exception occurs.
Some common Unchecked Exceptions in Java:
ClassCastException
IndexOutOfBoundsException
8
Scenario of Exceptions
9
10
Exception Handling in Java
try block: Java try block is used to enclose the code that might throw an
exception. It must be used within the method.
Java try block must be followed by either catch or finally block.
11
catch block: Java catch block is used to handle the Exception. It must be
used after the try block only.
You can use multiple catch block with a single try.
12
Internal working of try-catch block
13
Multi catch block: If we have to perform different tasks at the occurrence of
different Exceptions, then java multi catch block should be used.
14
nested try block: Sometimes a situation may arise where a part of a block may
cause one error and the entire block itself may cause another error. In such
cases, exception handlers have to be nested.
15
16
Throws keyword: The Java throws keyword is used to declare an exception. It gives
an information to the programmer that there may occur an exception so it is better for
the programmer to provide the exception handling code so that normal flow can be
maintained.
17
Throw keyword: The Java throw keyword is used to explicitly throw an exception.
The throw keyword is mainly used to throw custom exception.
18
Difference between throw and throws
19
finally block: Java finally block is used to to put "cleanup" code such as
closing a file, closing connection etc.
Java finally block is always executed whether exception is handled or not.
Java finally block must be followed by try or catch block.
20
21
Thank you
22