[go: up one dir, main page]

0% found this document useful (0 votes)
34 views31 pages

CHAPTER-5 Exception Handling

Java programming language based

Uploaded by

chikiihen
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)
34 views31 pages

CHAPTER-5 Exception Handling

Java programming language based

Uploaded by

chikiihen
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/ 31

CSEg2202

Object Oriented Programming

CHAPTER - 5

Exception Handling

2023
Content of the lecture

 Exception
 Types Of Exception
 Exception Handling
 Hierarchy of Exception Handling
 Try-Catch-Final Blocks,
 User Defined Exceptions
Exception Handling

 The process of converting system error messages into user friendly error
message is known as Exception handling

 Basically there are two types of error

• compile time error : It occurred due to poor understanding of lan-


guage
• Run time error : Occurred if user inputs invalid data
Types of Exception Handling

 In java there are two types of exception

1. Pre defined Exception

2. User defined exception

Predefined exception

 Are defined by sun microsystem and integrated in jdk to deal with universal
problems
 Predefined exception divided in two. they are
Types of Exception Handling
Asynchronous exception :This Exception deal with hardware related problem. There is pre

defined class Java.lang.Error that used to deal with those problems.

Synchronous Exception : Deal with programmatic error. To deal with those error ja-

va.lang.Exception is given in jdk.

 Synchronous exception categorized into two

 Checked exception

 Unchecked exception
Types of Exception Handling

 Checked exception is one which deal with compile time error. such as
class not found exception and Interface not found exception.
 Unchecked exception is one which deal with programmatic run time er-
ror. such are ArithemeticException , NumberFormatException , ArrayIn-
dexOutOfBoundException and etc
Hierarchy of Exception classes
Handling the Exception

 Use Five keywords for Handling the Exception


 try
 catch
 finally
 throws
 throw
Syntax
try
{
// statements causes problem at run time
}
catch(type of exception-1 object-1)
{
// statements provides user friendly error message
}
catch(type of exception-2 object-2)
{
// statements provides user friendly error message
}
finally
{
// statements which will execute compulsory
}
Exception Message Details
Exception message format:
[exception class]: [additional description of exception]
at [class].[method]([file]:[line number])

Example:
java.lang.ArrayIndexOutOfBoundsException: 2
at ExceptionExample.main(ExceptionExample.java:4)

 What exception class? ArrayIndexOutOfBoundsException


 Which array index is out of bounds? 2

 What method throws the exception? main


ExceptionExample.java
 What file contains the method?
4
 What line of the file throws the exception?
Example without Exception Handling
class ExceptionDemo
{
public static void main(String[] args)
{
int a=10, ans=0;
ans=a/0;
System.out.println("Denominator not be
zero");
}
}
Example with Exception Handling
class ExceptionDemo {
public static void main(String[] args)
{
try{
int a=10, ans=0;
ans=a/0;
System.out.println("Denominator not be
zero");
}catch(ArithmeticException e)
{System.out.println(“Denominator never
be Zero");}
}}
Output:
Denominator never be Zero
try and catch block

 Inside try block we write the block of statements which causes exceptions at
run time in other words try block always contains problematic statements.
 Important points about try block
 If any exception occurs in try block then CPU controls comes out of the try block and exe-
cutes appropriate catch block.
 After executing appropriate catch block, even through we use run time statement, CPU con-
trol never goes to try block to execute the rest of the statements.
 Each and every try block must be immediately followed by catch block that is no intermedi-
ate statements are allowed between try and catch block.
Syntax
try
{
.....
}
/* Here no other statements are allowed
between try and catch block */
catch()
{………..}

 Each and every try block must contains at least one catch block. But it is highly
recommended to write multiple catch blocks for generating multiple user
friendly error messages.
 One try block can contains another try block that is nested or inner try block
can be possible.
catch block

Inside catch block we write the block of statements which will generates user
friendly error messages.
catch block important points
 Catch block will be executed when exception occurs in try block.
 You can write multiple catch blocks for generating multiple user friendly error messages
to make your application strong. You can see below example.
 At a time only one catch block will execute out of multiple catch blocks.
finally Block in Exception Handling

 Inside finally block we write the block of statements which will relinquish
(released or close or terminate) the resource (file or database) where data
store permanently.
 finally block important points
 Finally block will execute compulsory
 Writing finally block is optional.
 You can write finally block for the entire java program
 In some of the circumstances one can also write try and catch block
in finally block.
Example
Catching Multiple Exceptions
 Handle multiple possible exceptions by multiple successive catch blocks
try {
// code that might throw multiple exception
}
catch (IOException e) {
// handle IOException and all subclasses
}
catch (ClassNotFoundException e2) {
// handle ClassNotFoundException
}

Rule: At a time only one Exception is occurred and at a time only one catch block is executed.

Rule: All catch blocks must be ordered from most specific to most general

i.e. catch for ArithmeticException must come before catch for Exception .
Example

class TestMultipleCatchBlock1{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(Exception e){System.out.println("common task completed");}
catch(ArithmeticException e)
{System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e)
{System.out.println("task 2 completed");}
System.out.println("rest of the code...");
}
}
Output:
Java Nested try block
 Java Nested try block: The try block within a try block is known as nested try block in java.
 Why use nested try block: Sometimes a situation may arise where a part of a block may cause on
error and the entire block itself may cause another error. In such cases, exception handlers have to b
nested. ....
Syntax: try
{ statement 1;
statement 2;
try
{ statement 1;
statement 2;
} catch(Exception e) {
} }
catch(Exception e)
{ }
....
Java nested try example
class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b=39/0;
}catch (ArithmeticException e){System.out.println("Division by zero");}
try{
int a[]=new int[5];
a[5]=4;
Java nested try example

}catch(ArrayIndexOutOfBoundsException e){System.out.println("Array Out of in-


dex");}

System.out.println("other statement");

}catch(Exception e){System.out.println("handeled");}

System.out.println("normal flow..");

}
Example : Multi catch block

 If you have to perform different tasks at the occurrence of different Exceptions,


use java multi catch block. Let's see a simple example of java multi-catch block.
public class TestMultipleCatchBlock{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e){System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
catch(Exception e){System.out.println("common task completed");}

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


} }
Output :task1 completed
rest of the code...
Throws

 The Java throws keyword is used to declare an exception. It gives an in-


formation 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.
 Syntax
Example
Throw

 Throw is a keyword in java language which is used to throw any user defined
exception to the same signature of method in which the exception is raised.
 Throw keyword always should exist within method body.
 whenever method body contain throw keyword then the caller method
should be followed by throws keyword.
 Syntax:
throw new exception_class("error message");
Example
rived class constructor.

Custom or User Defined Exception in Java
Save the program with public class name.java
Example
Difference between throw and throws in Java
Adama Science and Technology University
School of Electrical Engineering And Computing 2023 G.C

You might also like