Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 21

Exception Handling

•Exception Definition
•Exception Occurrence
•Exception Handling
•Exception Propagation
Exception Definition
• Treat exception as an object
• All exceptions are instances of a class
extended from Throwable class or its
subclass.

• Generally, a programmer makes new


exception class to extend the Exception
class which is subclass of Throwable class.
Hierarchical Structure of
Throwable Class
Object
Object

Throwable
Throwable

Error
Error Exception
Exception

... RuntimeException
RuntimeException
...

...
Definition of Exception
• Error Class
– Critical error which is not acceptable in normal
application program

• Exception Class
– Possible exception in normal application
program execution
– Possible to handle by programmer
System-Defined Exception
• Raised implicitly by system because of
illegal execution of program
• When cannot continue program execution
any more
• Created by Java System automatically
• Exception extended from Error class and
RuntimeException class
System-Defined Exception
• IndexOutOfBoundsException :
– When beyond the bound of index in the object which use index, such as
array, string, and vector
• ArrayStoreException :
– When assign object of incorrect type to element of array
• NegativeArraySizeException :
– When using a negative size of array
• NullPointerException :
– When refer to object as a null pointer
• SecurityException :
– When violate security. Caused by security manager
• IllegalMonitorStateException :
– When the thread which is not owner of monitor involves wait or notify
method
Programming in Java

Example 1 :-
public class Program1 {

public static void main(String [] args) {


Handling integer
int value1, value2, sum; values
value1 = Integer.parseInt(args[0]);
value2 = Integer.parseInt(args[1]); Integers of type - long, int
sum = value1 + value2; short or byte.
System.out.println(“Sum is “ + sum); Variable declaration.
} //end main Variables start with small
} //end class Program3
letter.
Integer.parseInt converts
strings to numbers.
Assignment statement
Number automatically
converted back to string
for display.
Programming in Java
Command-line arguments
Determining number of arguments
int numberOfArgs = args.length; //Note - no brackets
For any array, arrayName.length gives length
Conversion to integer
int value = Integer.parseInt(args[0]);
parseInt() raises NumberFormatException if a non numeric
value is entered.
Conversion to float
double volume = Double.parseDouble(args[1]);
Again this can raise NumberFormatException
Dealing with try {
exceptions value = Integer.parseInt(args[0]);
} //end try
catch(NumberFormatException nfe){
System.err(“Argument should be an integer”);
System.exit(-1);
} //end catch
Programming in Java
public class Program2 {
public static void main(String [] args) {
int value1, value2, sum; //declare variables
Revised version if ( args.length != 2 ) {
of addition System.err(“Incorrect number of arguments”);
program. System.exit(-1);
} //end if
try { //attempt to convert args to integers
Checks number value1 = Integer.parseInt(args[0]);
of arguments value2 = Integer.parseInt(args[1]);
} //end try
Checks that catch(NumberFormatException nfe) {
arguments are System.err(“Arguments must be integers”);
System.exit(-1);
numbers. } //end catch
sum = value1 + value2;
System.out.println(“Sum is “ + sum);
} //end main
} //end class Program3
Programming in Java
Prompted keyboard input
So far we have obtained program input from the command line arguments.

This limits us to only a few values and we are unable to prompt the user.

The usual way of getting input is to issue a prompt and then receive data from
the keyboard within the program as follows :-

import java.io.*; //provides visibility of io facilities


public class Greeting {
public static void main(String [] args) throws IOException {
String name;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(isr);
System.out.print(“Enter your name : “); //prompt for input
name = in.readLine(); //get it
System.out.println(“Welcome to Java - “ + name);
} //end main
} //end class Greeting
Programming in Java
Prompted keyboard input
Input operations can cause run-time exceptions. The previous program chose
not to catch them but to propogate them out of main - hence the throws
IOException clause. Here, we catch such exceptions within the program.

import java.io.*; //provides visibility of io facilities


public class Greeting {
public static void main(String [] args) {
String name;
try {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(isr);
System.out.print(“Enter your name : “); //prompt for input
name = in.readLine(); //get it
} //end try
catch(IOException ioe){}
System.out.println(“Welcome to Java - “ + name);
} //end main
} //end class Greeting
Programming in Java
Numeric input
Data is input as strings - just as with command-line input. If numeric input is
needed, explicit
conversion is import java.io.*; //provides visibility of io facilities
required with public class Greeting {
public static void main(String [] args) throws IOException {
Integer.parseInt() String line; int age; boolean ok = false;
or InputStreamReader isr = new InputStreamReader(System.in);
Double.parseDouble() BufferedReader in = new BufferedReader(isr);
while (!ok) {
try {
System.out.print(“Enter your age : “); //prompt for input
line = in.readLine(); //get string
age = Integer.parseInt();
ok = true;
} //end try
catch(NumberFormatException nfe){
System.err.println(“Integer value required”);
} //end catch
} //end while
System.out.println(“You are “ + age + “ years old”);
} //end main
} //end class Greeting
Programming in Java
A useful method
//method to prompt for and get int value in specified range
public static int getInt(String prompt, int min, int max) {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(isr);
boolean ok = false;
int result = 0;
while (!ok) {
try {
System.out.print(prompt); //prompt for input
result = Integer.parseInt( in.readLine() ); //get & convert it
if (result >= min && result <= max)
ok = true;
else
System.err.println(“Value must be between “ + min + “ and “ + max);
} //end try
catch(NumberFormatException nfe){
System.err.println(“Integer value required”);
} //end catch
catch(IOException e){}
} //end while
return result;
} //end getInt
Programming in Java
Reading text files
import java.io.*;
Note :- public class FileReadDemo {

public static void main(String [] args) throws IOException {


File not found excep.
FileReader fr = null;
Should be handled. try {
fr = new FileReader(args[0]);
Any number of files } //end try
catch(FileNotFoundException fnf){
may be open at once. System.err.println(“File does not exist”);
System.exit(-1);
Can use a constant } //end catch
string or variable to BufferedReader inFile = new BufferedReader(fr);
String line;
name file. while (inFile.ready()){
line = inFile.readLine();
Should close file at end System.out.println(line);
of program. } //end while
inFile.close();
} //end main

} //end class FileReadDemo


Programming in Java
Writing text files
Note :-

Text output to file uses same commands - print & println as


screen output.

Must call flush() and close() to ensure data is written to file.

import java.io.*;
public class FileWriteDemo {

public static void main(String [] args) throws IOException {


FileOutputStream fos = new FileOutputStream(args[0]);
PrintWriter pr = new PrintWriter(fos);
for ( int i = 0; i < 20; i++)
pr.println(“Demonstration of writing a text file”);
pr.flush();
pr.close();
} //end main

} //end class FileWriteDemo


Programming in Java - Exception handling

Exceptions are run-time errors which occur under exceptional


circumstances - i.e. should not normally happen.

In Java an exception is an instance of an Exception class which


is thrown by the offending code.

Exceptions, if not handled by the program will cause the


program to crash.

Exceptions are handled by catching them and dealing with the


problem.

Exceptions are propogated from a method to the caller back


through the chain of callee to caller.

If propogated out of main, they are always handled by the run


time system. (virtual machine).
Programming in Java - Exception handling

Exceptions are of different types and form a class hierarchy, just as other
classes do.

Any number of catch


public void methodA(){
methods may follow a //safe code
try block. try { //start of try block
//any number of statements
When an exception //that could lead to an exception
occurs, these are scanned } //end try block
in order, to find a catch(InterruptedException ie){
matching parameter. //code to deal with an IinterruptedException
} //end catch
catch(IOException ioe){
If one is found, the
//code to deal with an IOException
exception is cancelled }// end catch
and the handler code catch(Exception e){
executed. //code to deal with any Exception
}//end catch
All other catch methods //further code
are ignored. } //end methodA
Programming in Java - Exception handling
Exceptions are instances just like other class instances and can have
attributes and methods. This allows us to interrogate an exception
object to find out what
happened.
public void methodA(){
//safe code
The exception class is a try { //start of try block
sub-class of Throwable, //any number of statements
which provides the method //that could lead to an exception
printStackTrace() etc. } //end try block
catch(IOException ioe) {
The finally block following ioe.printStackTrace();
a try block is always System.out.println(“Exception handled”);
}//end catch
executed.
finally { //start finally block
//code always executed after we leave the
Users may create their //try block regardless of what else happens
own exceptions which }//end finally block
they can throw and //further code
handle in same way as } //end methodA
predefined ones.
Programming in Java - Exception handling
public class GarageFull extends Exception {
private int capacity; User-defined exceptions

public GarageFull(int s){


capacity = s; public class Garage {
}//end GarageFull private Vehicle[] fleet = new Vehicle[100];
private int count = 0;
public int getCapacity(){
return capacity; public void addVehicle(Vehicle v) throws GarageFull {
}//end getCapacity if (count =fleet.length)
throw new GarageFull(count);
} //end class GarageFull else
fleet[count++] = v;
}//end add Vehicle

try {
myGarage.addVehicle(new Car(“ABC123”,4));
} //end try
catch(GarageFull gf){
System.err.println(“Operation failed”);
System.err.println(“Capacity is “ + gf.getCapacity());
} //end catch
Programming in Java - Exception handling
Exception classes fall into two groups - sub-classes of RunTimeException
and others. In the case of others :-

A method which could give handle the exception


Object
Object
rise to an exception either locally.
by throwing it or calling
a method which might, This does not apply to
Throwable
Throwable
must declare the fact in a RunTimeExceptions.
throws clause, or
Exception
Exception

InterruptedException IOException
IOException RunTimeException ParseException
InterruptedException RunTimeException ParseException

IndexOutOfBoundsException
IndexOutOfBoundsException ArithmeticException
ArithmeticException NullPointerException
NullPointerException ArithmeticException
ArithmeticException
Programming in Java - Exception handling
public String getMessage() { //handles exception internally
String msg;
boolean ok = false;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(isr);
System.out.println(“Enter message “);
while (!ok){
try {
msg = in.readLine();
ok = true;
} //end try
catch(IOException ioe){
System.err.println(“Try again”);
}//end catch
}//end while public String getMessage() throws IOException { //does not
return msg; String msg;
} //end GetMessage InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(isr);
System.out.println(“Enter message “);
msg = in.readLine();
return msg;
} //end GetMessage

You might also like