Object oriented programming Chapter 05
Object oriented programming Chapter 05
Exception Handling
Slide 1
© Information Technology
Java Exceptions
In Java, an exception is an event/error condition that disrupts/changes the
normal flow of the program execution and It is an object which is thrown at
runtime.
When executing Java code, different errors can occur:
coding errors made by the programmer
errors due to wrong input, or
other unforeseen things.
In simple words, an exception is a problem that arises at the time of program
execution.
When an error occurs, Java will normally stop and generate an error message.
The technical term for this is: Java will throw an exception (throw an error).
Slide 2
© Information Technology
Reasons for Exception Occurrence
Several reasons lead to the occurrence of an exception. A few of them are as
follows.
When we try to open a file that does not exist may lead to an exception.
When enters array index out of bounds it may lead to an exception.
When the user enters invalid input data, it may lead to an exception.
When a network connection has lost during the program execution may
lead to an exception.
When we try to access the memory beyond the allocated range may lead to
an exception.
The physical device problems may also lead to an exception.
Slide 3
© Information Technology
Types of Exception
In java, exceptions have categorized into two types:
Checked Exception - An exception that is checked by the compiler at the
time of compilation is called a checked exception.
Unchecked Exception - An exception that can not be caught by the compiler
but occurrs at the time of program execution is called an unchecked
exception.
Java programming language has the following class hierarchy to
support the exception handling mechanism.
Slide 4
© Information Technology
Slide 5
© Information Technology
Exception Handling
How exceptions handled in Java?
• In java, the exception handling mechanisms uses the following five keywords
try, catch , throw, throws and finally
Exception handling is accomplished through the “try – catch” mechanism, or by a
“throws” clause in the method declaration.
For any code that throws a checked exception, you can decide to handle the exception
yourself, or pass the exception “up the chain” (to a parent class).
To handle the exception, you write a “try-catch” block. To pass the exception “up the
chain”, you declare a throws clause in your method or class declaration.
If the method contains code that may cause a checked exception, you MUST handle the
exception OR pass the exception to the parent class (remember, every class has Object
as the ultimate parent)
Slide 6
© Information Technology
Exception Handling
• Try-Catch Mechanism
• Wherever your code may trigger an exception, the normal code logic is placed
inside a block of code starting with the “try” keyword:
• After the try block, the code to handle the exception should it arise is placed in
a block of code starting with the “catch” keyword.
• You may also write an optional “finally” block. This block contains code that is
ALWAYS executed, either after the “try” block code, or after the “catch” block
code.
• Finally blocks can be used for operations that must happen no matter what
(i.e. cleanup operations such as closing a file)
Slide 7
© Information Technology
Exception Handling
• Syntax example
try {
//normal program code
}
catch(Exception e) {
//exception handling code
}
// it is optional to be with try –catch block
finally {
//The finally block executes always
}
Slide 8
© Information Technology
Exception Handling
Passing the exception(throws) mechanism
In any method that might throw an exception, you may declare the
method as “throws” that exception, and thus avoid handling the
exception yourself
• Example:
public void myMethod throws IOException {
//normal code with some I/O
}
Slide 9
© Information Technology
Exception Handling
All checked exceptions have class “Exception” as the parent class.
You can use the actual exception class or the parent class when referring to an
exception
Examples:
public void myMethod throws Exception {
public void myMethod throws IOException {
try { … }
catch (Exception e) { … }
try { … }
catch (IOException ioe) { … }
Slide 10
© Information Technology
import java.io.*;
public class CheckedExceptions {
public static void main(String[] args) {
File f_ref = new File("C:\\Users\\User\\Desktop\\Today\\Sample.txt");
try {
FileReader fr = new FileReader(f_ref);
}catch(Exception e) {
System.out.println(e);
}
}
}
Slide 11
© Information Technology
public class UncheckedException {
public static void main(String[] args) {
System.out.println("Beginning of the program");
//ArithmeticException:
try {
int i=100/0;
System.out.println(i);
Output
} catch (Exception e) {
System.out.println(e);
//ArrayIndexOutOfBoundsException:
try {
Beginning of the program
int a[]={};
System.out.println(a[0]); java.lang.ArithmeticException: / by zero
} catch (Exception e2) { java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
System.out.println(e2); java.lang.NumberFormatException: For input string: "abce"
} java.lang.NullPointerException
//NumberFormatException Final block execute allways
try {
End of the program
String str="abce";
int b=Integer.parseInt(str);
System.out.println(b);
} catch (Exception e3) {
System.out.println(e3);
}
//NullPointerException
try {
String str1=null;
int l=str1.length();
System.out.println(l);
} catch (Exception e4) {
System.out.println(e4);
}
} finally {
System.out.println("Final block execute always");
}
System.out.println("End of the program"); Slide 12
© Information Technology
}}
/*The throw keyword is used to throw an exception instance explicitly from a try block to
corresponding catch block.*/
import java.util.Scanner;
public class Sample {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1, num2, result;
System.out.print("Enter any two numbers: ");
num1 = input.nextInt();
num2 = input.nextInt();
try {
if(num2 == 0)
throw new ArithmeticException("Division by zero is not posible");
result = num1 / num2;
System.out.println(num1 + "/" + num2 + "=" + result);
}catch(ArithmeticException ae) {
System.out.println("Problem info: " + ae.getMessage());
}
System.out.println("End of the program");
}
}
Slide 13
© Information Technology
/*The throws keyword specifies the exceptions that a method can throw to the default handler and does not
handle itself.*/
import java.util.Scanner;
public class ThrowsExample {
int num1, num2, result;
Scanner input = new Scanner(System.in);
void division() throws ArithmeticException {
System.out.print("Enter any two numbers: ");
num1 = input.nextInt(); num2 = input.nextInt(); result = num1 / num2;
System.out.println(num1 + "/" + num2 + "=" + result);
}
public static void main(String[] args) {
ThrowsExample obj= new ThrowsExample();
try {
obj.division();
} catch(ArithmeticException ae) {
System.out.println("Problem info: " + ae.getMessage());
}
System.out.println("End of the program");
}
} Slide 14
© Information Technology
//The finally keyword used to define a block that must be executed irrespective of exception occurence.
import java.util.Scanner;
public class FinallyExample {
public static void main(String[] args) {
int num1, num2, result;
Scanner input = new Scanner(System.in);
System.out.print("Enter any two numbers: ");
num1 = input.nextInt(); num2 = input.nextInt();
try {
if(num2 == 0)
throw new ArithmeticException("Division by zero");
result = num1 / num2;
System.out.println(num1 + "/" + num2 + "=" + result);
} catch(ArithmeticException ae) {
System.out.println("Problem info: " + ae.getMessage());
}
finally {
System.out.println("The finally block executes always");
}
System.out.println("End of the program");
}
}
Slide 15
© Information Technology