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

Unit-1 Topic 1.3 - Exception Handling

Uploaded by

pappu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views

Unit-1 Topic 1.3 - Exception Handling

Uploaded by

pappu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

ADVANCE JAVA

PROGRAMMING
Unit-1
Prepared By: Ms. Ankita Sharma
Assistant Professor
Department of Computer Science
GTBIT, GGSIPU

Prepared by: Ms Ankita Sharma (Assistant Professor of CSE)


AGENDA
Exception Handling

Prepared by: Ms Ankita Sharma (Assistant Professor of CSE)


Agenda
• Introduction: Idea behind Exception
• Types of Exceptions
• Dealing With Exception
• Handling exception
• Displaying Exception Description
• Multiple Catch
• Nested try Catch block
• Use of throw
• Use of throws
• Use of finally
• Exception Objects
• User Defined Exception
• Checked and Unchecked Exception

Prepared by Ankita Sharma (Assistant Professor of CSE)


Idea Behind Exception
❑ Any software is not always fully error or bug free.
❑ Some errors are generated logically and not shown at the compile time of
the code.
❑ Some errors are left at the time of testing. These errors cannot be trapped at
the testing time because they are generated at run time.
• The Java programming language uses exceptions to handle errors and other
exceptional events.
• An exception is an event that occurs during the execution of a program that
disrupts the normal flow of instructions.
Introduction
• It can occur for various reasons say-
❑ A user has entered an invalid data
❑ File not found
❑ A network connection has been lost in the middle of communications
❑ The JVM has run out of a memory
Exception provides a mechanism to detect the origination of the errors,
cause of errors and forward the flow in other direction without halting the
system. The control flow will be redirected to handle it instead of shutting
down the system.
Introduction
• Java uses try-catch blocks and other keywords like finally, throw, and
throws to handle exceptions.
• JVM(Java Virtual Machine) by default handles exceptions, when an
exception is raised it will halt the execution of the program and throw
the occurred exception.
• Advantages of Exception Handling:
a) Separating Error-Handling Code from "Regular" Code
b) Propagating Errors Up the Call Stack
c) Grouping and Differentiating Error Types
Major reasons why an exception Occurs

• Invalid user input


• Device failure
• Loss of network connection
• Physical limitations (out-of-disk memory)
• Code errors
• Opening an unavailable file
❑Note: Errors represent irrecoverable conditions such as JVM running
out of memory, memory leaks, stack overflow errors, library
incompatibility, infinite recursion, etc.
❑Note: Errors are usually beyond the control of the programmer, and
we should not try to handle errors.
Types of Exceptions in Java
Types of Exceptions in Java

•.
Hierarchy of Java Exception Classes

• As java is an object-oriented language every class extends the Object


class.
• Throwable is the base/superclass of exception handling hierarchy in
java.
• Throwable is the top most class in the exception class hierarchy.
• All exceptions and errors are subclasses of the inbuilt class Throwable.
• There are two subclasses of Throwable, one is Exception class and
second is Error class.
Hierarchy of Java Exception Classes

• The Exception class is used for the exceptional conditions that are
handled by the programmer and they should catch it. Runtime
Exception is the important subclass of the Exception class. These types
of exceptions fired are automatically defined by the programs.
• The Error is another branch of Throwable; theses are the exceptions
that are not expected to be caught under normal conditions of the
programs. These are the errors occurred at the runtime and handled by
the run time environment. Stack overflow is an example.
Difference between Exception and Error

Exception Error
• Exceptions are unwanted conditions that • An error is also an unwanted condition
disrupt the flow of the program. but it is caused due to lack of resources
• Exceptions usually occur due to the code and indicates a serious problem.
and can be recovered.
• Exceptions can be of both • Errors are irrecoverable, they cannot be
checked(exceptions that are checked by handled by the programmers.
the compiler) and unchecked (exceptions
that cannot be checked by the compiler) • Errors are of unchecked type only.
type. • They can occur only at run time.
• They can occur at both run time and
compile time. • In java, errors belong to java.lang.error
• In Java, exceptions belong to class.
java.lang.Exception class. • Eg: OutOfMemmoryError.
How does a Programmer Handles an Exception?

• Customized exception handling in java is achieved using five


keywords: try, catch, throw, throws, and finally.
• Try block contains the program statements that may raise an
exception.
• Catch block catches the raised exception and handles it.
• Throw keyword is used to explicitly throw an exception.
• Throws keyword is used to declare an exception.
• Finally block contains statements that must be executed after the try
block.
Example of Exception Handling in Java

class ExceptionExample {
public static void main(String args[]) {
try {
// Code that can raise exception
int div = 509 / 0;
} catch (ArithmeticException e) {
System.out.println(e);
}
System.out.println("End of code");
}
}
Example of Exception Handling in Java
try block
• try block is used to execute doubtful statements which can throw exceptions.
• try block can have multiple statements.
• Try block cannot be executed on itself, there has to be at least one catch block or
finally block with a try block.
• When any exception occurs in a try block, the appropriate exception object will be
redirected to the catch block, this catch block will handle the exception according
to statements in it and continue the further execution.
• The control of execution goes from the try block to the catch block once an
exception occurs.
Syntax
try
{
//Doubtfull Statements.
}
catch block
• catch block is used to give a solution or alternative for an exception.
• catch block is used to handle the exception by declaring the type of exception within the
parameter.
• The declared exception must be the parent class exception or the generated exception type
in the exception class hierarchy or a user-defined exception.
• We can use multiple catch blocks with a single try block.
Syntax
try
{
//Doubtful Statements
}
catch(Exception e)
{

}
Programming examples using try-catch blocks

public class Main {


public static void main(String[ ] args) {
try {
int[] myNumbers = {10, 1, 2, 3, 5, 11};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}
}
Output
Something went wrong
Programming examples using try-catch
blocks
• In this program, the user has
declared an array myNumbers in
the try block, which has some
numbers stored in it.
• And the user is trying to access an
element of the array that is stored at
the 10th position.
• But array has only 6 elements and
the highest address position is 5. By
doing this user is trying to access
an element that is not present in the
array, this will raise an exception,
and the catch block will get
executed.
Multiple Catch Blocks
public class MultipleCatchBlock1 {
public static void main(String[] args) {

try {
int a[] = new int[5];
a[5] = 30 / 0;
} catch (ArithmeticException e) {
System.out.println("Arithmetic Exception occurs");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBounds Exception occurs");
} catch (Exception e) {
System.out.println("Parent Exception occurs");
}
System.out.println("End of the code");
}
}
Multiple Catch Blocks
Multiple Catch Blocks
• In this example, the try block has doubtful
statements that are trying to divide an
integer by 0 and 3 catch blocks which
have mentioned the exceptions that can
handle.
• After execution of the try block, the
Arithmetic Exception is raised and JVM
starts to search for the catch block to
handle the same.
• JVM will find the first catch block that
can handle the raised exception, and
control will be passed to that catch block.
• After the exception is handled the flow of
the program comes out from try-catch
block and it will execute the rest of the
code.
Multiple Catch Blocks Eg 2
Multiple Catch Blocks Eg 2
• In this example, try block has doubtful
statements that are trying to access
elements that are not present in an array
and 3 catch blocks that have mentioned
the exceptions that can handle.
• After execution of try block,
ArrayIndexOutOfBounds Exception is
raised and JVM starts to search for the
catch block to handle the same.
• JVM will find the second catch block that
can handle the raised exception, and
control will be passed to that catch block.
After the exception is handled the flow of
the program comes out from try-catch
block and it will execute rest of the code.
Nested Try Catch
Nested Try Catch

• As you can see that the ArrayIndexOutOfBoundsException occurred in the


grandchild try-block3.
• Since try-block3 is not handling this exception, the control then gets
transferred to the parent try-block2 and looked for the catch handlers in
try-block2.
• Since the try-block2 is also not handling that exception, the control gets
transferred to the main (grandparent) try-block where it found the
appropriate catch block for an exception.
• We can use the finally block after the main try-catch block if required.
printStackTrace()

• This method prints exception information in the format of the Name of


the exception: description of the exception, stack trace.
• There is a method of Throwable class printStackTrace() that gives the
complete stack trace, i.e. complete detail about the fired exception,
related message, exception class name, the method order in which it
was called and handled, the class and the method name in which it
fired, and with the line number.
//program to print the exception information using
printStackTrace() method

import java.io.*;

class GFG {
public static void main (String[] args) {
int a=5;
int b=0;
try{
System.out.println(a/b);
}
catch(ArithmeticException e){
e.printStackTrace();
}
}
}
Use of throw
• throw keyword in java is used to throw an exception explicitly.
• We can throw checked as well as unchecked exceptions using it.
• We specify the class of exception object which is to be thrown. The
exception has some error message with it that provides the error description.
• We can also define our own set of conditions for which we can throw an
exception explicitly using the throw keyword.
• The flow of execution of the program stops immediately after the throw
statement is executed and the nearest try block is checked to see if it has a
catch statement that matches the type of exception.
• It tries to find all the catch blocks until it finds the respective handler, else it
transfers the control to the default handler which will halt the program.
• Syntax:
throw new exception_class("error message");
Output
Exception in thread "main" java.lang.ArithmeticException: Access denied - You must be at least 18 years
old.
at Main.checkAge(Main.java:4)
at Main.main(Main.java:12)
Use of throws
• Some time it happens that the method can be a cause of any type of
exception but it doesn’t handle it.
• It must specify that the caller method must handle that exception. Do it
by including the throws clause in the method declaration or definition.
• A throws clause contains the list of exceptions that may be thrown. All
exceptions that method can throw must be declared in throws list.
• This is necessary for all exceptions, except those of type Error or
Runtime Exception, or any of their subclasses.
• Unchecked exception must be in throws list, if it is thrown by the
method.
• If they are not included compile time error will be generated.
Use of throws
• Syntax form of a method declaration that includes a throws clause:
Type method_name (parameter_list) throws exception_list
{
//body of method
}

Here, exception_list is a comma separated list of all the exceptions that


can be thrown by method.
Difference between throw and throws

throw throws
• Used to explicitly throw an • Used to declare an exception
exception. • Checked exceptions can be
• Checked exceptions cannot be propagated
propagated using throw only • Followed by a class
• Followed by an instance • Used with a method signature
• Used within a method • Can declare multiple exceptions
• Cannot throw multiple
exceptions
Use of finally
• finally block is associated with a try, catch block.
• It is executed every time irrespective of exception is thrown or not.
• finally block is used to execute important statements such as closing
statement, release the resources, and release memory also.
• finally block can be used with try block with or without catch block.
Use of finally • When exceptions are thrown, then
execution of the code is not linear, there
is a interruption. The subsequent
statements will never execute from
where the exception will be fired in the
block.
• If we want that, a set of instruction must
execute either the exception throw or
not, then the set of statements have to
be written in the finally block.
try
Use of finally {
//Doubtful Statements
}
catch(Exception e)
{

}
finally
{
//Close resources
}
public class Main {
public static void main(String[] args) {
try {
int data = 100/0;
System.out.println(data);
} catch (Exception e) {
System.out.println("Can't divide integer by 0!");
} finally {
System.out.println("The 'try catch' is finished.");
}
}
}
Use of finally
final finally finalize
finally block is used in java Exception
final is the keyword and access
Handling to execute the important finalize is the method in Java.
modifier
code after try-catch blocks.

final access modifier is used to apply finally block executes whether an finalize() method is used to perform
restrictions on the variables, methods, exception occurs or not. It is used to clean-up processing just before an
classes. close resources. object is a garbage collected.

It is used with variables, methods, and It is with the try-catch block in


Used with objects.
classes. exception handling.

Once declared, the final variable finalize method performs the cleaning
finally block cleans up all the
becomes constant and can't be with respect to object before its
resources used in the try block.
modified. destruction.

finally block executes as soon as the


execution of try-catch block is finalize method is executed just before
final is executed only when we call it.
completed without depending on the the object is destroyed.
exception.
Use of Exception Object
• The term exception is shorthand for the phrase "exceptional event“.
• When an error occurs within a method, the method creates an object and
hands it off to the runtime system.
• The object, called an exception object, contains information about the error,
including its type and the state of the program when the error occurred.
• Creating an exception object and handing it to the runtime system is
called throwing an exception.
• After a method throws an exception, the runtime system attempts to find
something to handle it.
• The set of possible "somethings" to handle the exception is the ordered list
of methods that had been called to get to the method where the error
occurred. The list of methods is known as the call stack (see the next
figure).
• The runtime system searches the call stack for a method that contains a block
of code that can handle the exception.
• This block of code is called an exception handler. The search begins with the
method in which the error occurred and proceeds through the call stack in the
reverse order in which the methods were called.
• When an appropriate handler is found, the runtime system passes the
exception to the handler.
• An exception handler is considered appropriate if the type of the exception
object thrown matches the type that can be handled by the handler.
• The exception handler chosen is said to catch the exception. If the runtime
system exhaustively searches all the methods on the call stack without finding
an appropriate exception handler, as shown in the next figure, the runtime
system (and, consequently, the program) terminates.
User-defined Custom Exception in Java

• Java provides us the facility to create our own exceptions which are
basically derived classes of Exception.
• Creating our own Exception is known as a custom exception or user-
defined exception.
• Basically, Java custom exceptions are used to customize the exception
according to user needs.
• In simple words, we can say that a User-Defined Exception or custom
exception is creating your own exception class and throwing that
exception using the ‘throw’ keyword.
User-defined Custom Exception in Java

Following are a few of the reasons to use custom exceptions:


• To catch and provide specific treatment to a subset of existing Java
exceptions.
• Business logic exceptions: These are the exceptions related to
business logic and workflow. It is useful for the application users or
the developers to understand the exact problem.
• In order to create a custom exception, we need to extend the
Exception class that belongs to java.lang package.
In order to create custom exception, we need to extend Exception class
that belongs to java.lang package.
Consider the following example, where we create a custom exception
named WrongFileNameException:

1. public class WrongFileNameException extends Exception {


2. public WrongFileNameException(String errorMessage) {
3. super(errorMessage);
4. }
5. }
Types of Exceptions Handling in Java

1. Checked Exceptions
• Checked exceptions are those exceptions that are checked at compile
time by the compiler.
• The program will not compile if they are not handled.
• These exceptions are child classes of the Exception class.
• IOException, ClassNotFoundException, InvocationTargetException,
and SQL Exception are a few of the checked exceptions in Java.
Types of Exceptions Handling in Java

2. Unchecked Exceptions
• Unchecked exceptions are those exceptions that are checked at run time by
JVM, as the compiler cannot check unchecked exceptions,
• The programs with unchecked exceptions get compiled successfully but
they give runtime errors if not handled.
• These are child classes of Runtime Exception Class.
• ArithmeticException, NullPointerException, NumberFormatException,
IndexOutOfBoundException are a few of the unchecked exceptions in Java.
Note: Please refer 3.13 Pg-96-97 of Kanika Lakhani Book for further
reading
Checked Exception Unchecked Exception
Occur at compile time. Occur at runtime.
The compiler checks for checked The compiler does not check for
exceptions. unchecked exceptions.
If checked exceptions are not handled If unchecked exceptions are not
we get a compile-time error. handled we get a run time error.
Can be handled at compile time. Can not be caught/handled at runtime.
They are direct subclasses of exception
They are subclasses of the Runtime
class but do not inherit Runtime
Exception class.
Exception Class.

Eg: ArithmeticException,
Eg: IOException, NullPointerException,
ClassNotFoundException, NumberFormatException,
SQLException are common checked StringIndexOutOfBoundException,
exceptions. ArrayIndexOutOfBound Exception are
common unchecked exceptions.
THANK YOU

Prepared by Ankita Sharma (Assistant Professor of CSE)

You might also like