Contents

advertisement
Topic 06
Contents
CS2312 Problem Solving and Programming | www.cs.cityu.edu.hk/~helena
Topic 06 -Exception Handling
I.
II.
III.
IV.
V.
VI.
VII.
VIII.
IX.
Introductory Examples (Example 1-5)
Exception Handling – Basic Idea
Exception Hierarchy
The Try-throw-catch Mechanism
Define our own exception classes (Example 6)
Pitfall: Catch the more specific exception first (Example 7)
The throws clause, throws clause in derived class (Example 8)
The Catch-or-Declare Rule, Checked Exceptions, Unchecked Exceptions
The Finally Block (Example 6')
I Introductory Examples
Files for testing:
Requirement: Read one positive integer from a file
Example 1 - Problems checked by Java Virtual Machine
Rundown 1.1:
Input the file pathname: c:\data001.txt
Data is: 678
Rundown 1.2:
Input the file pathname: c:\data02.txt
Exception in thread "main" java.io.FileNotFoundException at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.util.Scanner.<init>(Unknown Source)
at Main.main(Main.java:13)
Rundown 1.3:
Input the file pathname: c:\data002.txt
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Main.main(Main.java:14)
Last modified: 15‐Mar‐2016 • Problems are checked by Java Virtual
Machine
• java.io.FileNotFoundException and java.util.InputMismatchException are JAVA classes, each means a type of exception.
• JVM outputs the message by calling: public void printStackTrace()
[a method of the Java.lang.Throwable class]
1/12
Topic 06
CS2312 Problem Solving and Programming | www.cs.cityu.edu.hk/~helena
Files for testing:
Example 2 - We check and handle the problems ourselves
Below shows how that can be done, using try-catch blocks
Program:
Testing:
Rundown 2.1:
Input the file pathname: c:\data001.txt
Data is: 678
Rundown 2.2:
Input the file pathname: c:\data02.txt
Cannot open the file. Please check or ask CS2312 helpers.
Rundown 2.3:
Input the file pathname: c:\data002.txt
Cannot read the required number from the opened file. Please download from Helena's website again.
Last modified: 15‐Mar‐2016 We write code to check and take action (here simply output the situation)
2/12
Topic 06
CS2312 Problem Solving and Programming | www.cs.cityu.edu.hk/~helena
A common (better) style is:
1) Put the actions which may cause problem in one method, and
2) Place the try-catch blocks in a different method.
Example 3
public static void processFile(String fname) throws FileNotFoundException, InputMismatchException {
Scanner inFile = new Scanner(new File(fname));
int x = inFile.nextInt();
System.out.println("Data is: "+x); The throws clause – declare what inFile.close();
exceptions might occur.
}
public static void main(String[] args) {
try {
Scanner in = new Scanner(System.in);
System.out.print("Input the file pathname: ");
String fname = in.next();
processFile(fname);
in.close();
} catch (FileNotFoundException e) {
System.out.println("Cannot open the file. Please check or ask CS2312 helpers.");
} catch (InputMismatchException e) {
System.out.println("Cannot read the required number from the opened file. Please download from Helena's website again.");
} }
Rundown: [Same as 2.1, 2.2, 2.3 in Example 2]
We can write an Exception Controlled Loops
- Let the user get things right on a subsequent try
Example 4
public static void processFile(String fname) throws FileNotFoundException, InputMismatchException
{
Scanner inFile = new Scanner(new File(fname));
int x = inFile.nextInt();
System.out.println("Data is: "+x); inFile.close();
}
Rundown 4.1: public static void main(String[] args) Input the file pathname: c:\data002.txt {
Cannot read the required number from the opened file.
Scanner in = new Scanner(System.in);
boolean shouldEnd=false;
Try another file? Type your choice [y/n]: y while (!shouldEnd)
Input the file pathname: c:\data02.txt {
Cannot open the file. try {
Try another file? Type your choice [y/n]: y System.out.print("Input the file pathname: ");
Input the file pathname: c:\data001.txt String fname = in.next();
Data is: 678 processFile(fname);
shouldEnd=true;
} catch (FileNotFoundException e) {
System.out.println("Cannot open the file.");
System.out.print("Try another file? Type your choice [y/n]: ");
shouldEnd=(in.next().charAt(0)=='n');
} catch (InputMismatchException e) {
System.out.println("Cannot read the required number from the opened file.");
System.out.print("Try another file? Type your choice [y/n]: ");
shouldEnd=(in.next().charAt(0)=='n');
}
}
Rundown 4.2: in.close();
Input the file pathname: c:\data002.txt }
Cannot read the required number from the opened file. Try another file? Type your choice [y/n]: y Input the file pathname: c:\data02.txt Cannot open the file. Try another file? Type your choice [y/n]: n Last modified: 15‐Mar‐2016 3/12
Topic 06
CS2312 Problem Solving and Programming | www.cs.cityu.edu.hk/~helena
Create exception class + throw an exception object of the kind
- Suppose we expect a non-negative integer, however the file contains a –ve integer.
This is what we want:
If the file content is –ve, expected output is:
Rundown 5.1:
Input the file pathname: c:\data003.txt
Unexpected negative value from the file.
Try another file? Type your choice [y/n]: n
* This problem is not described by JAVA standard exception classes.
Therefore we create and use our own exception class.
Example 5
public class NegativeIntegerException extends Exception
{
public NegativeIntegerException() It is customary to give both a { default constructor and a super("Negative integer!"); constructor that contains a }
detailed message.
public NegativeIntegerException(String message) { super(message); }
}
processFile():
public static void processFile(String fname) throws FileNotFoundException,
InputMismatchException, NegativeIntegerException
{
Scanner inFile = new Scanner(new File(fname)); May throw FileNotFoundException
int x = inFile.nextInt();
May throw InputMismatchException
if (x<0)
throw new NegativeIntegerException();
throw NegativeIntegerException
System.out.println("Data is: "+x); inFile.close();
}
Inside main():
try {
System.out.print("Input the file pathname: ");
String fname = in.next();
processFile(fname);
shouldEnd=true;
}
catch (FileNotFoundException e) {
...
}
catch (InputMismatchException e) {
...
}
catch (NegativeIntegerException e) {
System.out.println("Unexpected negative value from the file.");
System.out.print("Try another file? Type your choice [y/n]: ");
shouldEnd=(in.next().charAt(0)=='n');
}
Last modified: 15‐Mar‐2016 4/12
Topic 06
CS2312 Problem Solving and Programming | www.cs.cityu.edu.hk/~helena
II Exception Handling – Basic Idea
Possible errors of a running JAVA program
1) User input error (e.g. typing mistake, wrong format of URL)
2) Device errors (e.g. printer suddenly jammed, webpage temporarily unavailable)
3) Physical limitation (e.g. disk full, out of memory)
4) Code error (e.g. invalid array index)
Error handling
1) [Traditional approach I ] Method returns -1, special end-of-file value, etc..
2) [Traditional approach II] Method returns a null reference.
3) JAVA’s exception handling:
[Mission]
Transfer control from the location where error occurred to an error handler
that can deal with the situation

throws an object that encapsulates the error information

the code section exits immediately

it does not return any value (even the method return type is not void)

Search for an exception handler that can deal with this particular error.
III Exception Hierarchy in JAVA
http://docs.oracle.com/j
avase/7/docs/api/java/u
til/InputMismatchExcep
tion.html
The Topmost Class: Throwable
http://docs.oracle.com/javase/7
/docs/api/java/lang/Throwable.
Last modified: 15‐Mar‐2016 5/12
Topic 06
The Exception Hierarchy:
CS2312 Problem Solving and Programming | www.cs.cityu.edu.hk/~helena
[http://docs.oracle.com/javase/7/docs/api/java/lang/Error.html]
• The Exception hierarchy indicates
conditions that a reasonable
application might want to catch.
(Ref. Examples 1-5)
The Error Hierarchy:
[http://docs.oracle.com/javase/7/docs/api/java/lang/Exception.html]
• The Error hierarchy describes internal
errors and resource exhaustion
situations which are abnormal.
Indicates serious problems that a
reasonable application should NOT try
to catch.
It should be aborted and the system (not our code) need to take over the control.
Note: Java programmers often call “Errors” as “Exceptions” as well. We speak in the
same way in this topic.
Examples:
java.lang.OutOfMemoryError (Ref. Lec06_Ex: out of heap space)
Program aborted by Object[] arr1 = new Object[10000000]; JAVA runtime
Object[] arr = arr1;
for (int i=0;i<17;i++)
Exception
in thread "main"
{
java.lang.OutOfMemoryError:
arr[0]=new Object[10000000];
Java heap space
arr=(Object[])arr[0];
at Main.main( Main.java:12)
}
java.lang.StackOverflowError (Ref. Lec06_Ex: recursion cannot stop)
private static int factorial(int n)
Program {
aborted by if (n==1) return 1;
JAVA runtime
else return n*factorial(n+1); Exception
in thread "main"
}
java.lang.StackOverflowError
at MainStackError.factorial(MainStackError.java:5)
public static void main(String[] args) at MainStackError.factorial(MainStackError.java:6)
{
at MainStackError.factorial(MainStackError.java:6)
System.out.println(factorial(4)); at MainStackError.factorial(MainStackError.java:6)
...
}
Last modified: 15‐Mar‐2016 6/12
Topic 06
CS2312 Problem Solving and Programming | www.cs.cityu.edu.hk/~helena
Catch an error and handle it, continue running.
[For illustration purpose only; recall: “a reasonable application should NOT try to catch”]
IV The Try-throw-catch Mechanism
The Try-throw-catch Mechanism:
The try block
•
Tells what to do when everything goes smooth
•
Can have code that throws exceptions for unusual conditions
•
If something goes wrong within the try block, execution in the try block is stoped and an
exception is thrown
The throw statement
•
Used to throw an exception
•
Syntax
•
Normally, after exception is thrown, the flow of control is transferred to a catch block, and the
catch block begins to run
throw new ExceptionClassName(arguments);
The catch block
• Tells what to do when an exception is caught
• One parameter, usually named “e” (but other names are also ok)
• Syntax
catch (ExceptionClassName e)
{
..code to handle the exception
}
Last modified: 15‐Mar‐2016 7/12
Topic 06
CS2312 Problem Solving and Programming | www.cs.cityu.edu.hk/~helena
V Define our own exception classes
Last modified: 15‐Mar‐2016 8/12
Topic 06
CS2312 Problem Solving and Programming | www.cs.cityu.edu.hk/~helena
VI Pitfall: Catch the more specific exception first
When we have 2 or more catch-blocks, catch the more specific exception first
Last modified: 15‐Mar‐2016 9/12
Topic 06
CS2312 Problem Solving and Programming | www.cs.cityu.edu.hk/~helena
VII The throws clause, throws clause in derived class
Last modified: 15‐Mar‐2016 10/12
Topic 06
CS2312 Problem Solving and Programming | www.cs.cityu.edu.hk/~helena
VIII The Catch-or-Declare Rule, Checked Exceptions, Unchecked Exceptions
Last modified: 15‐Mar‐2016 11/12
Topic 06
CS2312 Problem Solving and Programming | www.cs.cityu.edu.hk/~helena
IX The Finally Block
--- end ---
Last modified: 15‐Mar‐2016 12/12
Download