Lecture-1.3.4
Lecture-1.3.4
DEPARTMENT : CSE
Bachelor of Engineering (Computer Science & Engineering)
PROJECT BASED LEARNING IN JAVA
(22CST-359/22ITT-359)
TOPIC OF PRESENTATION:
Exception Handling
2
Exception Handling
JAVA - EXCEPTIONS
● An exception (or exceptional event) is a problem that arises during the execution of a program.
● When an Exception occurs the normal flow of the program is disrupted and the program/Application
terminates abnormally, which is not recommended, therefore, these exceptions are to be handled.
● An exception can occur for many different reasons. Following are some scenarios where an
exception occurs.
■ A user has entered an invalid data.
■ A file that needs to be opened cannot be found.
■ A network connection has been lost in the middle of communications or the JVM has run
out of memory.
● Some of these exceptions are caused by user error, others by programmer error, and others by
physical resources that have failed in some manner.
Error vs Exceptions
4
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 statements will be executed. That is why we use
exception handling in Java.
5
Java Exception Class Hierarchy
6
Checked Exceptions
13
Number Format Exception Example
14
ArrayIndexOutOfBoundsException
import java.io.*;
// Main class
class A {
18
How Programmer handles an exception?
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.
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.
Try Catch in Java – Exception handling
Try block
● The try block contains set of statements where an exception can occur.
● A try block is always followed by a catch block, which handles the exception
that occurs in associated try block.
● A try block must be followed by catch blocks or finally block or both.
• Syntax of try
• try{
• }catch(Exception_class_Name ref){}
● A single try block can have several catch blocks associated with it.
● When an exception occurs in try block, the corresponding catch block that
handles that particular exception executes.
● For example if an arithmetic exception occurs in try block then the statements
enclosed in catch block for arithmetic exception executes.
Rules about multiple catch blocks
● a single try block can have any number of catch blocks.
● A generic catch block can handle all the exceptions.
catch(Exception e){
//This catch block catches all the exceptions
}
● If no exception occurs in try block then the catch blocks are completely ignored.
● Corresponding catch blocks execute for that specific type of exception:
■ catch(ArithmeticException e) is a catch block that can hanlde
ArithmeticException
■ catch(NullPointerException e) is a catch block that can handle
NullPointerException
Multiple Catch Block Example
public class MultipleCatchBlock4 {
try{
String s=null;
System.out.println(s.length());
}
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("rest of the code");
}
23
}
Nested try Block Example
System.out.println("other statement");
}
//catch block of outer try block
catch(Exception e)
{
System.out.println("handled the exception (outer catch)");
}
System.out.println("normal flow..");
}
}
25
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.
26
Finally Block Example
public class TestFinallyBlock1{
public static void main(String args[]){
try {
27
throws Keyword
29
throw exception in java
● Throw keyword can also be used for throwing custom/user defined exceptions
● Program execution stops on encountering throw statement, and the closest catch statement is checked for matching type of
exception.
Syntax :
throw ThrowableInstance
Throw keyword Example
import java.io.*;
}
//main method
public static void main(String args[]){
try
{
method();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
System.out.println("rest of the code...");
}
} 31
public class TestThrow1 {
//function to check if person is eligible to vote or not
public static void validate(int age) {
if(age<18) {
//throw Arithmetic exception if not eligible to vote
throw new ArithmeticException("Person is not eligible to vote");
}
else {
System.out.println("Person is eligible to vote!!");
}
}
//main method
public static void main(String args[]){
//calling the function
validate(13);
System.out.println("rest of the code...");
}
}
32
Difference : final,finally,finalize
Sr. No. final finally finalize
1) Final is used to apply Finally is used to place Finalize is used to
restrictions on class, important code, it will perform clean up
method and variable. be executed whether processing just before
Final class can't be exception is handled object is garbage
inherited, final method or not. collected.
can't be overridden
and final variable
value can't be
changed.
2) Final is a keyword. Finally is a block. Finalize is a method.
User defined or custom exception in java
● In java we can create our own exception class and throw that exception using throw keyword. These exceptions
are known as user-defined or custom exceptions.
Syntax
While creating user defined exceptions, the following aspects have to be taken care :
a. The user defined exception class should extend from the Exception class and its subclass.
b. If we want to display meaningful information about the exception, we should override the toString() method.
For ex: If we are creating an application for handling the database of eligible voters, the age should be greater than or
equal to 18. In this case, we can create a user defined exception, which will be thrown in case the age entered is less
than 18.
User defined or custom exception in java
If you are creating your own Exception that is known as custom exception or user-defined
exception. Java custom exceptions are used to customize the exception according to user
need.
By the help of custom exception, you can have your own exception and message.
37
Thank you
38