Upload
xhienye
View
221
Download
0
Embed Size (px)
Citation preview
8/9/2019 Exceptions Details
1/21
Exception HandlingException DefinitionException Occurrence
Exception HandlingException Propagation
8/9/2019 Exceptions Details
2/21
Exception Definition
Treat exception as an object
All exceptions are instances of a class
extended from Throwable class oritssubclass.
Generally, a programmer makes new
exception class to extend the Exception
class which is subclass of Throwable class.
8/9/2019 Exceptions Details
3/21
Hierarchical Structure of
Throwable ClassObject
Throwable
Error Exception
RuntimeException
...
... ...
8/9/2019 Exceptions Details
4/21
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
8/9/2019 Exceptions Details
5/21
System-Defined Exception
Raised implicitly by system because of
illegal execution of program
When cannot continue program executionany more
Created by Java System automatically
Exception extended from Error class andRuntimeException class
8/9/2019 Exceptions Details
6/21
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
8/9/2019 Exceptions Details
7/21
Example 1 :-
Handling integer
values
public class Program1 {
public static void main(String [] args) {
int value1, value2, sum;
value1 = Integer.parseInt(args[0]);
value2 = Integer.parseInt(args[1]);
sum = value1 + value2;System.out.println(Sum is + sum);
} //end main
} //end class Program3
Integers of type - long, int
short or byte.Variable declaration.
Variables start with small
letter.
Integer.parseInt converts
strings to numbers.
Assignment statement
Number automatically
converted back to string
for display.
Programming in Java
8/9/2019 Exceptions Details
8/21
Command-line arguments
Determining number of arguments
int numberOfArgs = args.length; //Note - no bracketsFor 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
exceptions
try {
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
8/9/2019 Exceptions Details
9/21
public class Program2 {
public static void main(String [] args) {
int value1, value2, sum; //declare variables
if ( args.length != 2 ) {
System.err(Incorrect number of arguments);
System.exit(-1);
} //end if
try { //attempt to convert args to integers
value1 = Integer.parseInt(args[0]);
value2 = Integer.parseInt(args[1]);
} //end try
catch(NumberFormatException nfe) {
System.err(Arguments must be integers);
System.exit(-1);} //end catch
sum = value1 + value2;
System.out.println(Sum is + sum);
} //end main
} //end class Program3
Revised version
of addition
program.
Checks numberof arguments
Checks that
arguments are
numbers.
Programming in Java
8/9/2019 Exceptions Details
10/21
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
8/9/2019 Exceptions Details
11/21
Programming in Java
Prompted keyboard inputInput operations can cause run-time exceptions. The previous program chose
not to catch them but to propogate them out ofmain - 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
8/9/2019 Exceptions Details
12/21
Programming in Java
Numeric input
Data is input as strings - just as with command-line input. If numeric input is
needed, explicit
conversion is
required with
Integer.parseInt()
or
Double.parseDouble()
import java.io.*; //provides visibility of io facilities
public class Greeting {
public static void main(String [] args) throws IOException {
String line; int age; boolean ok = false;
InputStreamReader isr = new InputStreamReader(System.in);
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
8/9/2019 Exceptions Details
13/21
Programming in Java
A useful method
//method to prompt for and get int value in specified rangepublic 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
8/9/2019 Exceptions Details
14/21
Programming in Java
Reading text files
import java.io.*;public class FileReadDemo {
public static void main(String [] args) throws IOException {
FileReader fr = null;
try {
fr = new FileReader(args[0]);
} //end try
catch(FileNotFoundException fnf){
System.err.println(File does not exist);
System.exit(-1);
} //end catch
BufferedReader inFile = new BufferedReader(fr);
String line;
while (inFile.ready()){
line = inFile.readLine();System.out.println(line);
} //end while
inFile.close();
} //end main
} //end class FileReadDemo
Note :-
File not found excep.
Should be handled.
Any number of filesmay be open at once.
Can use a constant
string or variable to
name file.
Should close file at end
of program.
8/9/2019 Exceptions Details
15/21
Programming in Java
Writing text files
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
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.
8/9/2019 Exceptions Details
16/21
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 backthrough the chain of callee to caller.
If propogated out of main, they are always handled by the run
time system. (virtual machine).
8/9/2019 Exceptions Details
17/21
Programming in Java - Exception handling
public void methodA(){
//safe code
try { //start of try block
//any number of statements
//that could lead to an exception} //end try block
catch(InterruptedException ie){
//code to deal with an IinterruptedException
} //end catch
catch(IOException ioe){
//code to deal with an IOException
}// end catch
catch(Exception e){
//code to deal with any Exception
}//end catch
//further code
} //end methodA
Exceptions are of different types and form a class hierarchy, just as other
classes do.
Any number of catch
methods may follow a
try block.
When an exceptionoccurs, these are scanned
in order, to find a
matching parameter.
If one is found, the
exception is cancelledand the handler code
executed.
All other catch methods
are ignored.
8/9/2019 Exceptions Details
18/21
Programming in Java - Exception handling
public void methodA(){
//safe code
try { //start of try block
//any number of statements
//that could lead to an exception} //end try block
catch(IOException ioe) {
ioe.printStackTrace();
System.out.println(Exception handled);
}//end catch
finally { //start finally block
//code always executed after we leave the
//try block regardless of what else happens
}//end finally block
//further code
} //end methodA
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.
The exception class is a
sub-class ofThrowable,
which provides the methodprintStackTrace() etc.
The finally block following
a try block is always
executed.
Users may create their
own exceptions which
they can throw and
handle in same way as
predefined ones.
8/9/2019 Exceptions Details
19/21
Programming in Java - Exception handling
public class GarageFull extends Exception {
private int capacity;
public GarageFull(int s){
capacity = s;
}//end GarageFull
public int getCapacity(){
return capacity;
}//end getCapacity
} //end class GarageFull
User-defined exceptions
public class Garage {
private Vehicle[] fleet = new Vehicle[100];
private int count = 0;
public void addVehicle(Vehicle v) throws GarageFull {
if (count =fleet.length)throw new GarageFull(count);
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
8/9/2019 Exceptions Details
20/21
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
rise to an exception either locally.
by throwing it or calling
a method which might, This does not apply to
must declare the fact in a RunTimeExceptions.
throws clause, or
InterruptedException
ArithmeticException
Throwable
Object
ParseExceptionIOException
Exception
RunTimeException
IndexOutOfBoundsException ArithmeticExceptionNullPointerException
8/9/2019 Exceptions Details
21/21
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
return msg;} //end GetMessage
public String getMessage() throws IOException { //does not
String msg;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(isr);
System.out.println(Enter message );
msg = in.readLine();
return msg;
} //end GetMessage