0% found this document useful (0 votes)
17 views38 pages

Lecture-1.3.4

The document provides an overview of exception handling in Java, explaining its importance in maintaining the normal flow of applications when runtime errors occur. It categorizes exceptions into checked and unchecked types, outlines how the Java Virtual Machine (JVM) handles exceptions, and describes the use of keywords like try, catch, throw, throws, and finally for managing exceptions. Additionally, it includes examples of various exception types and how to implement exception handling in Java code.

Uploaded by

Abhinav Anand
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)
17 views38 pages

Lecture-1.3.4

The document provides an overview of exception handling in Java, explaining its importance in maintaining the normal flow of applications when runtime errors occur. It categorizes exceptions into checked and unchecked types, outlines how the Java Virtual Machine (JVM) handles exceptions, and describes the use of keywords like try, catch, throw, throws, and finally for managing exceptions. Additionally, it includes examples of various exception types and how to implement exception handling in Java code.

Uploaded by

Abhinav Anand
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/ 38

INSTITUTE : UIE

DEPARTMENT : CSE
Bachelor of Engineering (Computer Science & Engineering)
PROJECT BASED LEARNING IN JAVA
(22CST-359/22ITT-359)

TOPIC OF PRESENTATION:

Exception Handling

DISCOVER . LEARN . EMPOWER


Lecture Objectives

In this lecture, we will discuss:


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

• ClassNotFoundException: Class not found.


• CloneNotSupportedException: Attempt to clone an object that does not implement the
Cloneable interface.
• IllegalAccessException: Access to a class is denied. IllegalAccessException signals that a
particular method could not be found.
• InstantiationException: Attempt to create an object of an abstract class or interface.
• InterruptedException: One thread has been interrupted by another thread.
• NoSuchFieldException: A requested field does not exist.
• NoSuchMethodException: A requested method does not exist.
Runtime - Unchecked Exceptions
• ArithmeticException: Arithmetic error, such as divide-by-zero.
• ArrayIndexOutOfBoundsException: Array index is out-of-bounds.
• ArrayStoreException: Assignment to an array element of an incompatible type.
• IndexOutOfBoundsException: Some type of index is out-of-bounds.
• NegativeArraySizeException: Array created with a negative size.
• NullPointerException: Invalid use of a null reference.
• NumberFormatException: Invalid conversion of a string to a numeric format.
• SecurityException: Attempt to violate security.
• StringIndexOutOfBounds: Attempt to index outside the bounds of a string.
• TypeNotPresentException: Type not found. (Added by J2SE 5.)
• UnsupportedOperationException: An unsupported operation was encountered.
• ClassCastException: Invalid cast.
• EnumConstantNotPresentException: An attempt is made to use an undefined
enumeration value
• IllegalArgumentException: Illegal argument used to invoke a method.
• IllegalMonitorStateException: Illegal monitor operation, such as waiting on an unlocked
thread.
• IllegalStateException: Environment or application is in incorrect state.
• IllegalThreadStateException: Requested operation not compatible with the current thread
state.
Types

● Java’s exceptions can be categorized into two types:


1) Checked exceptions
2) Unchecked 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.
● Code that uses a checked exception will not compile if the catch or specify
rule is not followed.
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 6th element of the array then an
ArrayIndexOutOfBoundsExceptionexception occurs.
3.Errors − These are not exceptions at all, but problems that arise beyond the control of
the user or the programmer.
● Errors are typically ignored in your code because you can rarely do anything
about an error.
● For example, if a stack overflow occurs, an error will arise. They are also ignored
at the time of compilation.
How JVM handle an Exception?
Default 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.
Arithmetic Exception Example

public class JavaExceptionExample{


public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
catch(NULLPOINTER e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
12
Null pointer Example

public class JavaExceptionExample{


public static void main(String args[]){
try{
//code that may raise exception
String s=null;
System.out.println(s.length());//NullPointerException
}catch(ANullPointerException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}

13
Number Format Exception Example

public class JavaExceptionExample{


public static void main(String args[]){
try{
//code that may raise exception
String s=“ABC";
int i=Integer.parseInt(s);//NumberFormatException
}catch(NumberFormatException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}

14
ArrayIndexOutOfBoundsException

public class JavaExceptionExample{


public static void main(String args[]){
try{
//code that may raise exception
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
}catch(ArrayIndexOutOfBoundsException e)
{System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}
15
FileNotFoundException .

import java.io.*;

// Main class
class A {

// Main driver method


public static void main(String[] args)
{

// Reading file from path in local directory


FileReader file = new FileReader("C:\\test\\a.txt");

// Creating object as one of ways of taking input


BufferedReader fileInput = new BufferedReader(file);

// Printing first 3 lines of file "C:\test\a.txt"


for (int counter = 0; counter < 3; counter++)
System.out.println(fileInput.readLine());

// Closing file connections


// using close() method
fileInput.close();
}
} 16
IOException
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class FileNotFoundExceptionExample
{
public void checkFileNotFound()
{
try
{
FileInputStream in = new FileInputStream("input.txt");
System.out.println("This is not printed");
}
catch (FileNotFoundException fileNotFoundException)
{
fileNotFoundException.printStackTrace();
}
}
public static void main(String[] args)
{
FileNotFoundExceptionExample example = new FileNotFoundExceptionExample();
example.checkFileNotFound();
}
}E
17
Error Example

public class ErrorExample {


public static void main(String[] args){
recursiveMethod(10)
}
public static void recursiveMethod(int i){
while(i!=0){
i=i+1;
recursiveMethod(i);
}
}
}
Output
java.lang.StackOverflowError
at ErrorExample.ErrorExample(Main.java:42)

18
How Programmer handles an exception?

Customized 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.
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.
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{

• //code that may throw an exception

• }catch(Exception_class_Name ref){}

● While writing a program, if certain statements in a program can throw a


exception, enclosed them in try block and handle that exception
Catch block

● A catch block is where handle the exceptions are handled

● This block must follow the try block.

● A single try block can have several catch blocks associated with it.

● We can catch different exceptions in different catch blocks.

● 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 {

public static void main(String[] args) {

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

public class NestedTryBlock{


public static void main(String args[]){
//outer try block
try{
//inner try block 1
try{
System.out.println("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch(ArithmeticException e)
{
System.out.println(e);
}

//inner try block 2


try{
int a[]=new int[5];

//assigning the value out of array bounds


a[5]=4;
}
24
//catch block of inner try block 2
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}

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 {

System.out.println("Inside the try block");

//below code throws divide by zero exception


int data=25/0;
System.out.println(data);
}
//cannot handle Arithmetic type exception
//can only accept Null Pointer type exception
catch(NullPointerException e){
System.out.println(e);
}

//executes regardless of exception occured or not


finally {
System.out.println("finally block is always executed");
}

System.out.println("rest of the code...");


}
}

27
throws Keyword

● Throws keyword is used for handling checked exceptions


● 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 normal flow can be maintained.
returntype methodname() throws exception_list
{
//method code
}
● Any method that is capable of causing exceptions must list all the exceptions possible during its
execution, so that anyone calling that method gets a prior knowledge about which exceptions are to be
handled. A method can do so by using the throws keyword.
Throws keyword Example

public class TestThrows {


//defining a method
public static int divideNum(int m, int n) throws ArithmeticException {
int div = m / n;
return div;
}
//main method
public static void main(String[] args) {
TestThrows obj = new TestThrows();
try {
System.out.println(obj.divideNum(45, 0));
}
catch (ArithmeticException e){
System.out.println("\nNumber cannot be divided by 0");
}

System.out.println("Rest of the code..");


}
}

29
throw exception in java
● Throw keyword can also be used for throwing custom/user defined exceptions

● throw keyword is used to throw an exception explicitly.

● Only object of Throwable class or its sub classes can be thrown.

● 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.*;

public class TestThrow2 {

//function to check if person is eligible to vote or not


public static void method() throws FileNotFoundException {

FileReader file = new FileReader("C:\\Users\\Anurati\\Desktop\\abc.txt");


BufferedReader fileInput = new BufferedReader(file);

throw new FileNotFoundException();

}
//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

● class classname extends Exception


1. User-defined exception must extend Exception class.
2. The exception is thrown using throw keyword.

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.

Let's see a simple example of java custom exception.

class InvalidAgeException extends Exception{


InvalidAgeException(String s){
super(s);
}
}
User defined or custom exception in java
class TestCustomException1{
static void validate(int age)throws InvalidAgeException{
if(age<0)
throw new InvalidAgeException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
try{
validate(13);
}catch(Exception m){System.out.println("Exception occured: "+m);}

System.out.println("rest of the code...");


}
}
Output: Exception occured: InvalidAgeException:not valid
rest of the code...
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/138-a2973
dc6-c024-4d81-be6d-5c3344f232ce.pdf

37
Thank you

38

You might also like