Final Unit-V
Final Unit-V
Contents:-
Types of Exceptions
1
Exception Handling
Exception Handling:
An unexpected, unwanted event which disturbs the normal flow of the program
is noting but exception.
The exception handling in java is one of the powerful mechanism to handle the
runtime errors so that normal flow of the application can be maintained.
2
Exception Handling
Exception Handling:
The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application that
is why we use exception handling.
3
Exception Handling
Exception Handling:
4
Exception Handling
Exception Hierarchy:
5
Exception Handling
Exception Handling:
Errors Exceptions
Errors in java are of type java.lang.Error. Exceptions in java are of type java.lang.Exception.
Examples :
Examples : Checked Exceptions : SQLException, IOException
java.lang.StackOverflowError, Unchecked Exceptions :
java.lang.OutOfMemoryError ArrayIndexOutOfBoundException, ClassCastException,
NullPointerException
6
Exception Handling
Language level.
Type conversion; illegal values, improper casts.
Bounds violations; illegal array indices.
Bad references; null pointers.
Program level.
User defined exceptions.
7
Exception Handling
Exceptions can be generated by the Java run-time system, or they can be manually
generated by your code
Java exception handling is managed by five keywords: try, catch, throw, throws,
and finally
Program statements which are error prone, put that code into try block.
If an exception occurs within the try block, it is thrown. Code within catch block
will do the desired operation and handle it.
Sub class cannot throw more Exceptions than the super class.
If the method throwing an exception does not catch it , the method must declare
that it throws that exception.
8
Exception Handling
Keywords in Exception
Keyword Description
try The "try" keyword is used to specify a block where we should place
exception code. The try block must be followed by either catch or finally.
It means, we can't use try block alone.
finally The "finally" block is used to execute the important code of the
program. It is executed whether an exception is handled or not.
9
Exception Handling
Uncaught Exception:
When we don’t handle Exception in Java, it is passed to Java’s default Exception
handler. This handler prints the description of Exception on the console and the
program terminates on the same line. This abrupt termination of program leads
user to the confusion. To avoid this we have to have Exception Handling code in
program.
Code-1
10
Exception Handling
11
Exception Handling
Code-2
12
Exception Handling
Multiple Catch:
A code in which there are chances of multiple Exception can be put in a try block
followed by multiple catch block. When an Exception is raised in try block, the
control of the program is passed to all catch block sequentially and whenever
exception object matches, the corresponding catch block is executed.
Code-3
13
Exception Handling
There are mainly two types of exceptions: checked and unchecked. Here, an error
is considered as the unchecked exception
1. Checked Exception
2. Unchecked Exception
Checked Exception
14
Exception Handling
IllegalAccessException IndexOutOfBoundsException
--ArrayIndexOutOfBoundsException
--StringIndexOutOfBoundsException
NoSuchFieldException NullPointerException
NoSuchMethodException InputMismatchException
InterruptedException EmptyStackException
IOException IllegalArgumentException
--NumberFormatException
15
Exception Handling
IllegalAccessException ClassCastException
NoSuchFieldException NegativeArraySizeException
NoSuchMethodException SecurityException.
InterruptedException, IOException
EOFException, FileNotFoundException
InterruptedIOException,
InvalidClassException,
InvalidObjectException
SocketException, MalformedURLException
ProtocolException , UnknownHostException
SQLException , BatchUpdateException
SQLDataException
16
Exception Handling
Nested try:
In nested try block when an exception is raised in inner try, the control is the
program is passed to the inner catch, but if inner catch cannot handle it, it is
passed to outer catch for handling.
Code-4:
17
Exception Handling
Code-5: 18
Exception Handling
When we rethrow an exception from a method it becomes an uncaught exception in a method. The
person who wants to call this method should call it with proper try catch arrangement. Though this
increases the responsibility of an user, it facilitates him with a freedom to take corresponding action
on exception.
Code-6: 19
Exception Handling
“throws” keyword:
This keyword is used to intimate the user about the uncaught exception in method. This
keyword is attached in method name followed by names of exception class.
For some exception it is compulsory to write throws clause. Such Exception are known as
checked exception and other exceptions are known as unchecked exception.
Code-8:
20
Exception Handling
Throw VS Throws:
throw throws
Java throw keyword is used to explicitly Java throws keyword is used to declare an exception.
throw an exception.
Checked exception cannot be propagated Checked exception can be propagated with throws.
using throw only.
Throw is used within the method. Throws is used with the method signature.
You cannot throw multiple exceptions. You can declare multiple exceptions e.g.
public void method()throws
IOException,SQLException.
21
Exception Handling
Finally keyword:
If an exception is created in try block, the control of the program is passed to catch block
following that try block. This skips the code in try block after exception.
But sometimes such code may contain some important logic which has to be executed in any
situation(Input/Output, Closing of files, Database connection, socket). We put such code in
finally block. The finally block is executed before passing control to catch block.
22
Exception Handling
Finally keyword:
Code-9:
23
Exception Handling
Creating User defined Exception:
Java provides us facility to create our own exceptions which are basically derived classes
of Exception. The exceptions that are created by user are called as user defined exception.
Code-10:
Q1. Write an application that will accept age from user and find whether it is greater than 18
or not. If it is less than 18 generate an user defined exception “Not Eligible for Voting”.
Code-11:
Q2.Write an application that will accept name from employee and find whether it is valid
employee , if valid then show appropriate message otherwise generate an user defined exception
“Exception: NameIsInvalid”.
Code-12:
Q3. Write a class Driver with attributes vehicle no, name & age. Initialize values through
parameterized constructor. If age of driver is less than 18 then generate user-defined exception
“AgeNotWithinTheRange”.
Code-13: 24
Exception Handling
Creating User defined Exception:
Q4. Write a java program to accept name from user. If the name contains a non-
alphabetical character, raise an Exception “InvalidNameException.
Code-14:
25