Professional Documents
Culture Documents
Lecture # 13
1
Course Books
Text Books:
Cay S. Horstmann, Big Java: Early Objects, Wiley, 7th Edition
Herbert Schildt, Java: A Beginner's Guide, McGraw-Hill Education,
Eighth Edition
2
Course Instructors
4
Common Runtime Errors
Dividing a number by zero.
Accessing an element that is out of bounds of an array.
Trying to store incompatible data elements.
Using negative value as array size.
Trying to convert from string data to a specific data value
(e.g., converting string “abc” to integer value).
File errors:
opening a file in “read mode” that does not exist or no read
permission
Opening a file in “write/update mode” which has “read only”
permission.
Corrupting memory: - common with pointers
Any more ….
5
Runtime Errors
1 import java.util.Scanner;
2
3 public class ExceptionDemo {
4 public static void main(String[] args) {
5 Scanner scanner = new Scanner(System.in);
6 System.out.print("Enter an integer: ");
7 int number = scanner.nextInt();
8 If an exception occurs on this
9 line, the rest of the lines in the // Display the result
method are skipped and the System.out.println(
10
program is terminated.
11 "The number entered is " + number);
12 }
13 }
Terminated.
6
Exception Classes
ClassNotFoundException
IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException
VirtualMachineError
Error
AWTError
7
System Errors
ClassNotFoundException
IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException
8
Exceptions
Exception describes ClassNotFoundException
errors caused by your
program and external IOException
circumstances. These ArithmeticException
errors can be caught Exception AWTException
and handled by your NullPointerException
program. RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException
VirtualMachineError
Error
AWTError
9
Runtime Exceptions
ClassNotFoundException
IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException
10
Without Error Handling – Example 1
class NoErrorHandling{
public static void main(String[] args){
int a,b;
a = 7;
b = 0;
Program does not reach here
System.out.println(“Result is “ + a/b);
System.out.println(“Program reached this line”);
}
} No compilation errors. While running it reports an error and stops without
executing further statements:
java.lang.ArithmeticException: / by zero at Error2.main(Error2.java:10)
11
Traditional way of Error Handling -
Example 2
class WithErrorHandling{
public static void main(String[] args){
int a,b;
a = 7; b = 0;
if (b != 0){
System.out.println(“Result is “ + a/b);
}
else{
Program reaches here
System.out.println(“ B is zero);
}
System.out.println(“Program is complete”);
}
}
12
Error Handling
Any program can find itself in unusual
circumstances – Error Conditions.
13
Exceptions
Exception is a run-time error which arises during
the execution of java program. The term
exception in java stands for an exceptional event.
It can be defined as abnormal event that arises
during the execution and normal flow of program.
An exception is a condition that is caused by a
runtime error in the program.
Provide a mechanism to signal errors directly
without using flags.
Allow errors to be handled in one central part of the
code without cluttering code.
14
Exceptions and their Handling
When the JVM encounters an error such as
divide by zero, it creates an exception object and
throws it – as a notification that an error has
occurred.
If the exception object is not caught and handled
properly, the interpreter will display an error and
terminate the program.
If we want the program to continue with
execution of the remaining code, then we should
try to catch the exception object thrown by the
error condition and then take appropriate
corrective actions. This task is known as
exception handling.
15
Common Java Exceptions
ArithmeticException
ArrayIndexOutOfBoundException
ArrayStoreException
FileNotFoundException
IOException – general I/O failure
NullPointerException – referencing a null object
OutOfMemoryException
SecurityException – when applet tries to perform an
action not allowed by the browser‟s security setting.
StackOverflowException
StringIndexOutOfBoundException
16
Exception hierarchy
Java organizes exceptions in inheritance tree:
Throwable
Error
Exception
RuntimeException
TooManyListenersException
IOException
AWTException
All Exceptions are inherited from Runtime Exception.
An Exception is a class.
String is a property of throwable class and whenever exception occur JRE
passes a message.
Exceptions in Java
A method can signal an error condition by
throwing an exception – throws
The calling method can transfer control to a
exception handler by catching an exception - try,
catch
Clean up can be done by - finally
Try and Catch ,Finally are bound to each other.
Try must be with Catch or Finally.
Sequence is Try,Catch,Finally. Nothing can be
written b/w Try and Catch blocks.
JVM always catch Exception(by default).
18
Exception Handling Mechanism
try Block
Throws
exception
catch Block
Object
Statements that
handle the exception
19
Syntax of Exception Handling Code
…
…
try {
// statements
}
catch( Exception-Type e)
{
// statements to process exception
}
..
..
20
With Exception Handling - Example 3
class WithExceptionHandling{
public static void main(String[] args){
int a,b; float r;
a = 7; b = 0;
try{
r = a/b;
System.out.println(“Result is “ + r);
Program Reaches here
}
catch(ArithmeticException e){
System.out.println(“ B is zero);
}
System.out.println(“Program reached this line”);
}
} 21
With Exception Handling - Example 4
Class ExampleException{
public static void main(String args[]){
division(2,0);
System.out.print(“return from main”);
}
static void division(int i,int j)
try{ The type of exception raised contain
System.out.print(“i/j”+i/j);} same
type of object throw i.e Arithmetic
catch(Arithmetic Exception e) Exception
{System.out.print(“catch”);
}
System.out.print(“return from division”); }
22
With Exception Handling - Example 4
output
If i=2 and j=4
return from division
return from main
If i=10 and j=0 Exception get at
o/p is catch System.out.print(i/j);
23
Multiple Catch Statements
A try block can be followed by one or more catch
blocks. Each catch block must contain a different
exception handler. So, if you have to perform
different tasks at the occurrence of different
exceptions, use java multi-catch block.
At a time only one exception occurs and at a
time only one catch block is executed.
All catch blocks must be ordered from most
specific to most general, i.e. catch for
ArithmeticException must come before catch for
Exception.
Multiple Catch Statements
If a try block is likely to raise more than one type of exceptions, then
multiple catch blocks can be defined as follows:
…
…
try {
// statements
}
catch( Exception-Type1 e)
{
// statements to process exception 1
}
..
..
catch( Exception-TypeN e)
{
// statements to process exception N
}
…
25
With Exception Handling - Example 5
Class ExampleException{
public static void main(String args[]){
division(2,0);
System.out.print(“return from main”); }
static void division(int i,int j){
int iArray={1,2,3};
The type of try{ System.out.print(“i/j”+(i/j));
exception raised for(int i=0;i<=3;i++)
contain same { System.out.print(iArray[i]);
type of object } }
throw i.e Arithmetic
Exceptioncatch(ArithmeticException e)
{System.out.print(“catch”);}
catch(ArrayIndexOutOfBoundException e)
{System.out.print(“Index OutOfBound”);}
}
26
finally block
Java supports definition of another block called finally that be used to
handle any exception that is not caught by any of the previous statements. It
may be added immediately after the try block or after the last catch block:
…
try {
// statements
}
catch( Exception-Type1 e)
{
// statements to process exception 1
}
finally {
….
}
When a finally is defined, it is executed regardless of whether or not an
exception is thrown. Therefore, it is also used to perform certain house
keeping operations such as closing files and releasing system resources.
If exception is raised in try and catched the abrupt termination then the code
after finally execute.
If exception is raised in try but not catched than the finally is execute but
code after finally does not execute.
27
With Exception Handling - Example 6
Class ExampleException{
public static void main(String args[]){
try{
division(2,0);}
finally{
System.out.print(“finally”);
}
System.out.print(“return from main”);
}
static void division(int i,int j){
System.out.print(“i/j”+i/j);}
System.out.print(“return from division”); }
28
With Exception Handling - Example 6 output
Division(2,0)
finally
Exception in thread "main"
java.lang.ArithmeticException: / by zero
at exception.Example6.division(Example6.java:23)
at exception.Example6.main(Example6.java:16)
Division(2,2)
i/j 1
return from division
finally
Return from main
29
Catching and Propagating Exceptions
30
Catching and Propagating Exceptions
If an exception is raise in try but not catch than it goes to finally but
if finally also throw some other exception then the rest of code is not
execute and the last abrupt exception is throw by default handler.
catch (ArthematicException e){
s.o.p(“except caught”);
}
throw e;
}
//goes to default handler as we run in sequence.
31
With Exception Handling - Example 7
class WithExceptionCatchThrow{
public static void main(String[] args){
int a,b; float r; a = 7; b = 0;
try{
r = a/b;
System.out.println(“Result is “ + r);
}
Program Does Not
reach here
catch(ArithmeticException e){
when exception occurs System.out.println(“ B is zero);
throw e;
}
System.out.println(“Program is complete”);
}
} 32
With Exception Handling - Example 8
class WithExceptionCatchThrowFinally{
public static void main(String[] args){
int a,b; float r; a = 7; b = 0;
try{
r = a/b;
System.out.println(“Result is “ + r);
}
Program reaches catch(ArithmeticException e){
here System.out.println(“ B is zero);
throw e;
}
finally{
System.out.println(“Program is complete”);
}
}
}
33
Using printStackTrace and
getMessage
Class Throwable
Superclass of all exceptions
Offers method printStackTrace
Prints method call stack for caught Exception object
Most recent method on top of stack
Helpful for testing/debugging
Constructors
Exception()
Exception( String informationString )
informationString may be accessed with method
getMessage
With Exception Handling - Example 9
Call method1, which calls method2,
class WithExceptionCatchThrows{ which calls method3, which throws
public static void main(String[] args){ an exception.
try{
method1();
}
catch(Exception e){ getMessage prints the
System.err.println( e.getMessage() + "\n" ); String the Exception was
e.printStackTrace(); initialized with.
} printStackTrace prints the
} methods in this order:
public static void method1() throws Exception{ method3
method2
method2(); method1
} main
public static void method2() throws Exception{ (order they were called when
method3();} exception occurred)
public static void method3() throws Exception{
throw new Exception( "Exception thrown in method3" );
} 35
}
With Exception Handling - Example 9 output
36
Execution of try catch blocks
For normal execution:
try block executes, then finally block executes, then other
statements execute
When an error is caught and the catch block throws an
exception or returns:
try block is interrupted
catch block executes (until throw or return statement)
finally block executes
When error is caught and catch block doesn‟t throw an
exception or return:
try block is interrupted
catch block executes
finally block executes
other statements execute
When an error occurs that is not caught:
try block is interrupted
finally block executes
Summary
38