0% found this document useful (0 votes)
14 views29 pages

9 Exception Handling

The document provides an overview of Exception Handling in Java, explaining its importance in maintaining the normal flow of applications during runtime errors. It details the types of exceptions (checked and unchecked), the process of implicit and explicit exception handling, and the use of keywords such as try, catch, throw, throws, and finally. Additionally, it includes examples and best practices for implementing exception handling in Java programs.

Uploaded by

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

9 Exception Handling

The document provides an overview of Exception Handling in Java, explaining its importance in maintaining the normal flow of applications during runtime errors. It details the types of exceptions (checked and unchecked), the process of implicit and explicit exception handling, and the use of keywords such as try, catch, throw, throws, and finally. Additionally, it includes examples and best practices for implementing exception handling in Java programs.

Uploaded by

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

Name of the School: School of Computer Science and

Engineering

DEPARTMENT OF COMPUTER SCIENCE


& ENGINEERING
Subject Name: Java Programming
Topics Covered: Exception Handling

1
Faculty Name: Dr. Jitender Tanwar Programe Name: B.Tech
Exception Handling in Java
The Exception Handling in Java is one of the powerful mechanism to handle
the runtime errors so that the normal flow of the application can be maintained.
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 need to handle exceptions. Let's consider a scenario:
statement 1;
statement 2;
Statement 3;//exception occurs
statement 4;
statement 5;
Suppose there are 5 statements in a Java program and an exception occurs at
statement 3; the rest of the code will not be executed, i.e., statements 4,5 will not
be executed. However, when we perform exception handling, the rest of the
2
statements will be executed. That is why we use exception handling in Java.
Types of Exceptions

1. Checked exceptions
 A checked exception is an exception that occurs at the compile time.
 These are also called as compile time exceptions.
 These exceptions cannot simply be ignored at the time of
compilation, the programmer should take care of (handle) these
exceptions.
 checked exceptions are subject to the catch or specify a requirement,
which means they require catching or declaration. This requirement
is optional for unchecked exceptions.
 Code that uses a checked exception will not compile if the catch or
specify rule is not followed.
3
Types of Exceptions contd.

2. Unchecked exceptions − An unchecked exception is an exception that


occurs at the time of execution.
 These are also called as Runtime Exceptions.
 These include programming bugs, such as logic errors or
improper use of an API. Runtime exceptions are ignored at the
time of compilation.
 For example, if you have declared an array of size 5 in your
program, and trying to call the 6 th element of the array then an
ArrayIndexOutOfBoundsException occurs.

4
Implicit Exception Handling
Whenever inside a method, if an exception has occurred, the method creates an Object known as
Exception Object and hands it off to the run-time system(JVM).
The exception object contains name and description of the exception, and current state of the program
where exception has occurred.
Creating the Exception Object and handling it to the run-time system is called throwing an Exception.
There might be the list of the methods that had been called to get to the method where exception was
occurred. This ordered list of the methods is called Call Stack.

Now the following procedure will happen.


The run-time system searches the call stack to find the method that contains block of code that can
handle the occurred exception. The block of the code is called Exception handler.
The run-time system starts searching from the method in which the exception occurred, and proceeds
through the call stack in the reverse order in which methods were called.
If it finds an appropriate handler then it passes the occurred exception to it. An appropriate handler
means the type of the exception object thrown matches the type of the exception object it can handle.
If the run-time system searches all the methods on the call stack and couldn’t have found the
appropriate handler then the run-time system handover the Exception Object to the default exception
handler,
5
which is part of the run-time system. This handler prints the exception information and
terminates the program abnormally.
Explicit Exception Handling
 Java exception handling is managed via five keywords: try, catch, throw,
throws and finally.
 Program statements that can raise exceptions are contained within a try block.
 If an exception occurs within the try block, it is thrown.
 System-generated exceptions are automatically thrown by the Java run-time
system. To manually throw an exception, use the keyword throw.

6
Try :- Java try block is used to enclose the code that might throw an exception.
It must be used within the method.
If an exception occurs at the particular statement in the try block, the rest of the
block code will not execute. So, it is recommended not to keep the code in try
block that will not throw an exception.
Java try block must be followed by either catch or finally block.

Catch:- Java 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 ( i.e., Exception) or the generated exception type. However, the good
approach is to declare the generated type of exception.
The catch block must be used after the try block only. You can use multiple catch
block with a single try block.
A try block can be followed by one or more catch blocks. Each catch block must
7
contain a different exception handler. So, if you have to perform different tasks at
the occurrence of different exceptions, use java multi-catch block.
Syntax of Java try-catch

try{
//Block of code that may throw an exception
}
catch(Exception_class_Name ref){
// Block of code to handle exception
}

8
public class ExceptionDemo { Try-Catch Example
public static void main (String[] args) {
int a=10;
for(int i=3;i>=0;i--)
Try
try block contains the code
{
that might throw an exception.
System.out.println(a/i);
Don’t write anything extra in
}catch(ArithmeticException e){
try as statements after the
System.out.println(e);
exception will not get executed
}}}
if the exception occurred.

OUTPUT:
3
5
10
java.lang.ArithmeticException:
9 / by zero
public class ExceptionDemo {
public static void main (String[] args) { int a=10;
for(int i=3;i>=0;i--)
try{ System.out.println(a/i);
}}} Try must be immediately
followed by catch or finally
block

prog.java:5: error: 'try' without 'catch', 'finally' or resource


declarations
try{
^ 1 error

10
public class ExceptionDemo {
public static void main (String[] args) {
The catch block is
int a=10;
used to catch the
for(int i=3;i>=0;i--)
exception thrown
try{ System.out.println(a/i);
by statements in
}
the try block. The
System.out.println("between try and catch");
catch must follow
catch(ArithmeticException e)
try else it will give a
{ System.out.println(e); } } }
compile-time error.

prog.java:5: error: 'try' without 'catch', 'finally' or resource declarations

try{ ^ prog.java:9: error: 'catch' without 'try'


catch(ArithmeticException e){

^
11
2 errors
class Main { Do not keep any
public static void main (String[] args) { code after the
try { statement which
System.out.println(4/0); is prone to
//will not get printed exception.
System.out.println("end of try!"); Because if an
} catch(ArithmeticException e) exception
{ System.out.println("divide by 0"); } } } occurred, it will
straight away
jump to the catch
or finally block,
Output: ignoring all other
divide by 0 statements in the
try block.

12
Exact Exception
class Main { public static void main (String[] args) { try{
While catching
System.out.println(4/0);
} //ArithmeticException the exception in
catch(ArithmeticException e){ System.out.println("divide by the catch block,
0"); } } } either you can
have directly the
Output: class of exception
divide by 0 or its superclass.

Superclass of Exact
Exception
class Main { public static void main (String[] args) {
try{
System.out.println(4/0);
} //superclass of ArithmeticException
catch(Exception e){ System.out.println("divide by 0"); } } }
Output:
divide by 0
13
Multiple Catch Block: We can have multiple catch blocks, But we you
have to maintain the hierarchy from subclass to superclass.

class Main {
public static void main (String[] args) {
try{ System.out.println(4/0);
}catch(ArithmeticException e) {
System.out.println("ArithmeticException : divide by 0");
}catch(Exception e) {
System.out.println("Exception : divide by 0");
}}}

Output:
ArithmeticException: Divide by 0

14
Finally Block
Contains code that must be executed no matter if an exception is
thrown or not. It contains code of file release, closing connections,
class
etc. Main {
public static void main (String[] args) {
try{ System.out.println(4/0);
}catch(Exception e) Finally, will execute
{ even when we do
System.out.println(e); not handle
} exceptions.
finally { Before halting the
System.out.println("finally executed"); } program, JVM checks
System.out.println("end"); } } if there is a “finally”
block.
Output: java.lang.ArithmeticException: / by zero
finally executed
15 end
Throw Keyword
It is a keyword that is used to explicitly throw an exception.
We can use throw where according to our logic an exception should
occur.
public class ExceptionDemo {
static void canVote(int age){
if(age<18)
try{
throw new Exception();
}catch(Exception e)
{
System.out.println("you are not an adult!");
} else
{System.out.println("you can vote!"); }
public static void main (String[] args) { Output:
canVote(20); you can vote!
canVote(10); you are not an adult!
}16 }
Throws Keyword
• Throws keyword is used when callee doesn’t want to handle the
exception rather it wants to extend this responsibility of handling the
exception to the caller of the function.
• Basically says what sort of exception the code can throw and relies on
the caller to handle it.
• It is used to handle checked Exceptions as the compiler will not allow
code to compile until they are handled.
public class ExceptionDemo {
static void func(int a) throws Exception{
System.out.println(10/a);
}
public static void main (String[] args) {
try{ Output:
func(10); 1 can't divide by zero
func(0); }catch(Exception e)
{17System.out.println("can't divide by zero"); } } }
Thank you

18
19
20
21
Java Exception Class Hierarchy

22
Error vs Exceptions

23
Finally
Java finally block is a block used to execute important code such as
closing the connection, etc.
 Java finally block is always executed whether an exception is handled or
not. Therefore, it contains all the necessary statements that need to be
printed regardless of the exception occurs or not.
 Why use Java finally block?
 finally block in Java can be used to put "cleanup" code such as closing a
file, closing connection, etc.
 The important statements to be printed can be placed in the finally block.

24
Throw
The Java throw keyword is used to throw an exception explicitly.
 We specify the exception object which is to be thrown. The Exception
has some message with it that provides the error description. These
exceptions may be related to user inputs, server, etc.
 We can throw either checked or unchecked exceptions in Java by throw
keyword. It is mainly used to throw a custom exception.
 The syntax of the Java throw keyword is given below.
 throw Instance i.e.,
 throw new exception_class("error message");

25
Throws
 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 the normal flow of the program can be maintained.
 Exception Handling is mainly used to handle the checked exceptions. If
there occurs any unchecked exception such as NullPointerException, it is
programmers' fault that he is not checking the code before it being used.

Syntax of Java throws


return_type method_name() throws exception_class_name{
//method code
}
26
Exception Handling Keywords

27
Some technical interview questions:
1. Can we override a super class method which is throwing an unchecked
exception with checked exception in the sub class?
2. What Is a Chained Exception in Java?
3. What is unreachable catch block error?
4. What Is the Try-With-Resources Statement?
5. Will it be possible to only include a ‘try’ block without the ‘catch’ and
‘finally’ blocks?

28
References:
 https://www.geeksforgeeks.org/
 https://www.javatpoint.com/exception-handling-in-java
 https://www.tutorialspoint.com/java/java_exceptions.htm
 The complete reference, eleventh edition, available at:
https://gfgc.kar.nic.in/sirmv-science/GenericDocHandler/1
38-a2973dc6-c024-4d81-be6d-5c3344f232ce.pdf

29

You might also like