Unit-1 Topic 1.3 - Exception Handling
Unit-1 Topic 1.3 - Exception Handling
PROGRAMMING
Unit-1
Prepared By: Ms. Ankita Sharma
Assistant Professor
Department of Computer Science
GTBIT, GGSIPU
•.
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?
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
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
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
}
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.
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.
• 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
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