0% found this document useful (0 votes)
23 views

Final Unit-V

Uploaded by

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

Final Unit-V

Uploaded by

blahhwhocares69
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 25

Unit-V Exception Handling

Contents:-

Fundamentals of Exception Handling


Types of Exceptions

 Keywords used in Exception handling

 Multiple catch clauses

Nested try Statements


Java Built in Exceptions


User Defined Exceptions.


1
Exception Handling
Exception Handling:

An unexpected, unwanted event which disturbs the normal flow of the program
is noting but exception.

Objective of Exception Handling: Graceful termination of program(We should not


miss anything).

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.

Exception is abnormal termination of program due to breaking of fundamental


rules of Java. Exception is an object of particular class which is subclass of
RuntimeException.

2
Exception Handling

Exception Handling:

A Java exception is an object that describes an exceptional condition that has


occurred in a piece of code.

When an exceptional condition arises, an object representing that exception is


created and thrown in the method that caused the error.

Meaning of Exception: Defining alternative way to continue rest of the program


normally is the concept of 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.

Exceptions include both checked as well as unchecked


All errors in java are unchecked type.
type.

Checked exceptions are known to compiler where as


Errors happen at run time. They will not be
unchecked exceptions are not known to compiler
known to compiler.
because they occur at run time.

You can recover from exceptions by handling them


It is impossible to recover from errors.
through try-catch blocks.

Errors are mostly caused by the environment in


Exceptions are mainly caused by the application itself.
which application is running.

Examples :
Examples : Checked Exceptions : SQLException, IOException
java.lang.StackOverflowError, Unchecked Exceptions :
java.lang.OutOfMemoryError ArrayIndexOutOfBoundException, ClassCastException,
NullPointerException

6
Exception Handling

Exceptions can occur at many levels:

Hardware/Operating system level.


 Arithmetic exceptions; divide by 0, under/overflow.
 Memory access violations; segfault, stack over/underflow.

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.

catch The "catch" block is used to handle the exception. It must be


preceded by try block which means we can't use catch block alone. It
can be followed by finally block later.

finally The "finally" block is used to execute the important code of the
program. It is executed whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.


throws The "throws" keyword is used to declare exceptions. It doesn't
throw an exception. It specifies that there may occur an exception in the
method. It is always used with method signature.

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

 The code in which there are chances of Exception is put in


try-block. The code in try- block is considered under
monitoring. When an Exception is raised in try –block. The
control of the program is passed to the catch block
followed by try-block

 The catch block accepts the object of corresponding


Exception class and holds the code necessary to handle
Exception. After execution of catch block, the code after
catch is executed. The code in try block after exception is
skipped because catch is never called from try.

 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

Types of Java Exceptions:

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

The classes which directly inherit Throwable


class except RuntimeException and Error
are known as checked exceptions e.g.
IOException, SQLException etc.
Checked exceptions are checked at compile-time.

14
Exception Handling

Types of Java Exceptions:


Unchecked Exception
The classes which inherit RuntimeException are known as unchecked exceptions
e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at
compile-time, but they are checked at runtime.

Checked Exception Unchecked Exception


ClassNotFoundException ArithmeticException

IllegalAccessException IndexOutOfBoundsException
--ArrayIndexOutOfBoundsException
--StringIndexOutOfBoundsException
NoSuchFieldException NullPointerException

NoSuchMethodException InputMismatchException

InterruptedException EmptyStackException

IOException IllegalArgumentException
--NumberFormatException

15
Exception Handling

Checked Exception Unchecked Exception


ClassNotFoundException ArrayStoreException

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

Class ArithmeticException extends RuntimeException


{
public String toString( )
{
return”Java.lang.ArithmeticException:\ by zero”;
}
}

Code-5: 18
Exception Handling

throw” keyword: It is used to throw exception object explicitly

 Sequence of events for throw: Sequence of events for throw:

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

To rethrow an exception using throw” keyword:


Code-7:

“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 followed by an instance. Throws is followed by class.

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

You might also like