Title: Things that can go wrong
1Things 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.
2Exceptions
In Java, they are classes
- Throwing Exceptions is Javas 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)
3Exception 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
4Generating 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.jav
a14) at ExceptionEx.main(ExceptionEx.java2
7)
stack trace
5Categories 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. - 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.
These represent some error, not programmers
fault, but the programmer can (should) do
something about it
They are programmers fault, the compiler
cant do a thing.
6Unchecked Exceptions handle
- Logic error The program is incorrect ?
- Environment error - e.g. out of memory
- I/O error e.g., lost network connection.
Checked Exceptions handle
7Javas Exception Hierarchy
Page. 112
Unchecked
Checked
8Example 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(FileNotFoundExcepti
on ex) System.out.println(ex.getMessage())
System.exit(1) while
(in.hasNextLine()) String aLine
in.nextLine() wordNo aLine.length()
in.close() return wordNo
9Try-Catch-Finally Blocks
try 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 finall
y this block is optional this block will
execute whether or not an exception is thrown
10Example of Try-Catch-Finally Blocks
int a new int3 int sum 0 double
q0 a00a11a22 for (int
i0ilt5i) try sum ai q
ai/sum System.out.println("\nquotient is
"q) catch (IndexOutOfBoundsException ioobe)
System.out.println("\nThe array is too
small!") catch (ArithmeticException e)
System.err.printf("\nErrors\n",e) finally
System.out.println("Sum is "sum) System.out.pr
intln("All is cool\n")
Throwing runtime/uncheck exceptions is
controversial
Errorjava.lang.ArithmeticException / by
zero Sum is 0 All is cool quotient is
1.0 Sum is 1 All is cool quotient is 0.0 Sum
is 3 All is cool The array is too small! Sum
is 3 All is cool The array is too small! Sum
is 3 All is cool
11The programmer can throw Exceptions
- e.g., to complain about methods pre-conditions
that are not met
Example // expects its argument to be greater
than 0. setLength( double theLength ) What
to do when that precondition isnt met?
? throw an exception!
12Throwing an Exception
Document that the method throws an exception
/ Set the length dimension of this
ltttgtRectanglelt/ttgt. _at_param theLength the new
length of this ltttgtRectanglelt/ttgt
must be gt 0 _at_throws IllegalArgumentException
if ltttgttheLengthlt/ttgt is lt 0. / public void
setLength( double theLength ) if ( theLength
lt 0 ) throw new IllegalArgumentException(Il
legal Rectangle length (
theLength ) must be gt 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.
13- public class HandleExceptions
- public static void main(String args)
- System.out.println("Testing Exception
Handling\n") - try
- int i1,j2
- Exception myExnull
- String s"0.2"
- iInteger.parseInt(s)
- if (i gt j)
- throw new RuntimeException()
- int A new int5
- i1
- if (ilt2 igt4)
- throw new IndexOutOfBoundsExceptio
n() - i 5
- i Ai
-
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!!")
14A well designed method should throw appropriate
exceptions. (API)
15Custom Exception Classes
Create a custom unchecked exception class simply
by extending RuntimeException and providing two
constructors. Everything else you need is
inherited from Throwable!
package gray.adts.shapes / 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() public ShapeException(
String errMsg ) super( errMsg )
extends Exception for unchecked