Chapter 1: Title

Download Report

Transcript Chapter 1: Title

Things that can go wrong
What do we do?
• Logic error – The program is incorrect 
• Environment error - e.g. out of memory
• I/O error – e.g., lost network connection.
4/2/2016
ITK 275
1
Exceptions
In Java, they are classes
• Throwing Exceptions is Java’s way of telling you something
has gone wrong
• When an “exceptional condition” occurs, an exception object
is created storing information about the nature of the exception
(kind, where it occurred, etc.). When this happens, we say that
“an exception is thrown”.
• The JVM looks for a block of code to catch and handle the
exception (do something with it)
4/2/2016
ITK 275
2
Exception throwing
bad thing happens
The sequence of throwing
exceptions
method c
 exception occurs
X
If the exception cannot
be handled here, it will
continue to throw back
method b  method c()
method a  method b()
main() calls  method a()
JVM starts application at
main()
The sequence of calling
4/2/2016
ITK 275
3
Generating an ArithmeticException
8 /**
9
* Compute quotient of numerator / denominator.
10 * Assumes denominator is not 0.
11 */
12 public static int computeQuotient(int numerator,
13
int denominator) {
14
return numerator / denominator;
15 }
Enter two integers: 8 0
Exception in thread “main” java.lang.ArithmeticException: / by zero
at ExceptionEx.computeQuotient(ExceptionEx.java:14)
stack trace
at ExceptionEx.main(ExceptionEx.java:27)
4/2/2016
ITK 275
4
Categories of exceptions
These categorization affect compile-time behavior only
• Checked exceptions – descended from class Exception, but
outside the hierarchy rooted at RuntimeException. The compiler will
check that you either catch or re-throw checked exceptions.
These represent some error, not programmer’s fault, but
the programmer can (should) do something about it
• Unchecked exceptions – (aka Runtime Exception )
represent the kinds of errors your program can avoid through careful
programming and testing. The compile does not check to see that you
handle these exceptions.
They are programmer’s fault, the compiler can’t
do a thing.
4/2/2016
ITK 275
5
Unchecked Exceptions handle:
• Logic error – The program is incorrect 
Checked Exceptions handle:
• Environment error - e.g. out of memory
• I/O error – e.g., lost network connection.
4/2/2016
ITK 275
6
Java’s Exception Hierarchy
Page. 112
Unchecked
Checked
Example of handling a checked exception
public static int countCharsInAFile(String str) {
Scanner in =null;
int wordNo = 0;
try {
File file = new File(str);
in = new Scanner(file);
}
catch(FileNotFoundException ex) {
System.out.println(ex.getMessage());
System.exit(1);
}
while (in.hasNextLine()) {
String aLine = in.nextLine();
wordNo += aLine.length();
}
in.close();
return wordNo;
}
4/2/2016
ITK 275
8
try {
Try-Catch-Finally Blocks
program statements; some of which may throw an exception
}
catch ( ExceptionType1 exception ) {
program statements to handle exceptions of type ExceptionType1
or any of its subclasses
}
catch ( ExceptionType2 exception ) {
program statements to handle exceptions of type ExceptionType2
or any of its subclasses
}
…
...
other catch clauses
…
catch ( ExceptionTypeN exception ) {
program statements to handle exceptions of type ExceptionTypeN
or any of its subclasses
}
finally {
this block is optional;
this block will execute whether or not an exception is thrown
}
Example of Try-Catch-Finally Blocks
int[] a = new int[3];
int sum = 0;
Throwing runtime/uncheck exceptions is controversial
double q=0;
a[0]=0;a[1]=1;a[2]=2;
for (int i=0;i<5;i++)
Error:java.lang.ArithmeticExcept
try {
ion: / by zero
Sum is 0
sum += a[i];
All is cool
q = a[i]/sum;
***
System.out.println("\nquotient is "+q);
quotient is 1.0
}
Sum is 1
catch (IndexOutOfBoundsException ioobe)
All is cool
{
***
System.out.println("\nThe array is too
quotient is 0.0
small!");
Sum is 3
}
All is cool
***
catch (ArithmeticException e)
{
The array is too small!
System.err.printf("\nError:%s\n",e);
Sum is 3
All is cool
}
***
finally {
System.out.println("Sum is "+sum);
The array is too small!
Sum is 3
System.out.println("All is cool\n***");
All is cool
}
***
4/2/2016
ITK 275
10
The programmer can throw Exceptions
e.g., to complain about method’s pre-conditions that are
not met
Example:
// expects its argument to be greater than 0.
setLength( double theLength )
What to do when that precondition isn’t met?
 throw an exception!
4/2/2016
ITK 275
11
Throwing an Exception
Document that the method throws an exception
/**
* Set the length dimension of this <tt>Rectangle</tt>.
* @param theLength the new length of this <tt>Rectangle</tt>;
*
must be > 0
* @throws IllegalArgumentException if <tt>theLength</tt> is <= 0.
*/
public void setLength( double theLength ) {
if ( theLength <= 0 )
throw new IllegalArgumentException(“Illegal Rectangle length (“ +
theLength + ”): must be > 0 “);
this.length = theLength;
}
Create an exception object the way you create any other kind of object, with new.
Throw the exception with the reserved word throw.
4/2/2016
ITK 275
12
public class HandleExceptions {
public static void main(String[] args) {
System.out.println("Testing Exception Handling\n");
try {
int i=1,j=2;
catch (NumberFormatException ex) {
System.out.println("\n"+ex.toString());
ex.printStackTrace();
}
catch (IllegalArgumentException ex) {
System.out.println("\n"+ex.toString());
ex.printStackTrace();
}
catch (ArrayIndexOutOfBoundsException ex) {
System.out.println("\n"+ex.toString());
ex.printStackTrace();
}
catch (IndexOutOfBoundsException ex) {
System.out.println("\n"+ex.toString());
ex.printStackTrace();
}
catch (RuntimeException ex) {
System.out.println("\n"+ex.toString());
ex.printStackTrace();
}
finally {
System.out.println("\nWe are done. Finally!!");
}
Exception myEx=null;
String s="0.2";
i=Integer.parseInt(s);
if (i > j)
throw new RuntimeException();
int[] A = new int[5];
i=1;
if (i<2 || i>4)
throw new IndexOutOfBoundsException();
i = 5;
i = A[i];
}
catch (ArithmeticException ex) {
System.out.println("\n"+ex.toString());
ex.printStackTrace();
catch (NullPointerException ex) {
System.out.println("I'm here 12345");
System.out.println("\n"+ex.toString());
ex.printStackTrace();
}
4/2/2016
}
}
ITK 275
13
A well designed method should throw
appropriate exceptions. (API)
4/2/2016
ITK 275
14
Custom Exception Classes
package gray.adts.shapes;
Create a custom unchecked exception class
simply by extending RuntimeException
and providing two constructors. Everything
else you need is inherited from Throwable!
/**
* The exception that is thrown whenever an operation on a
* shape is in violation of a method pre-condition.
*/
public class ShapeException extends RuntimeException {
public ShapeException() {
super();
}
extends
public ShapeException( String errMsg ) {
super(“ “ + errMsg );
}
Exception
for unchecked
}
4/2/2016
ITK 275
15