COMP1008 Exceptions: Runtime Error
COMP1008 Exceptions: Runtime Error
Runtime Error
Unexpected error that terminates a program.
Undesirable
COMP1008 Exceptions
This message is displayed when the code is executed. You typically see a call stack trace.
Stack
A stack is a last-in first-out queue: Items are pushed on, and popped off the pile. Can use an ArrayList to store stack contents.
java.lang.NullPointerException at T10.main(T10.java:7)
(So references are really pointers according to the JVM!)
Pop
Push
Top of stack
Class Stack
class Stack<T> { private ArrayList<T> contents; public Stack()
{ contents = new ArrayList<T>();} // Methods push, pop, top ...
This is a generic Stack class. T is a type variable that is instantiated with a real type in a declaration.
How can you force someone to take notice when these kinds of errors are made?
Best answer: Use test-first programming.
(Non) Solution 1
Ignore the problem and hope it never happens! Relies on object always being used correctly...
10
Solution 3
Solution 4
Bad design to put output into data structure class like this. Don't do it!
public T pop() { if (contents.size() == 0) // empty { return null; // silent default action if empty } else { return contents.remove(0); } }
Cant avoid noticing this! But still little information about where and why.
Take some default action and rely on client code doing right thing with result. But moves problem somewhere else, without compiler checking correctness.
12
11
Solution 5
public T pop() throws EmptyStackException { if (contents.size() == 0) // empty { throw new EmptyStackException(); } // Note no return needed here else { return contents.remove(0); } }
Force the program to deal with the error or terminate. Force the compiler to check code. Force the programmer to write the code properly.
13
14
Try and catch try { a.doSomething() ; } catch (Exception e) { // Handle the exception }
A try block tries to execute statements.
15
16
Catch
catch (Exception e) { ... }
This catches an object of library class Exception or any of its subclasses. Typically, your exceptions are subclasses of class Exception.
catch (MyException e) { ... }
A subclass extends another class. Exception represents exceptions in general, a subclass represents a specific kind of exception like EmptyStackException.
17
18
Finally finally
try { f() ; } catch (MyException e) // optional { // Do something } finally { // Guaranteed to execute // this whatever happens. }
2006, Graham Roberts
19
20
class Throwable
Throwable provides:
A String to store a message about an exception. A method String getMessage() to return the message string. A method printStackTrace. And a few other methods.
21
22
Questions?
An Example
public void f(String s) // s should represent an integer. { int tmp ; try { tmp = Integer.parseInt(s) ; // This can fail } catch (NumberFormatException e) { tmp = -1 ; // Set tmp to some default value } // Carry on and use tmp }
23
24
Integer.parseInt public static int parseInt (String s) throws NumberFormatException { return parseInt(s,10) ; } parseInt is overloaded and calls another version of parseInt that can throw an exception. This version does not catch the exception but declares that it can occur.
Throws keyword A method can directly or indirectly throw an exception without catching it.
the exception must be declared by a throws declaration, for class Exception and subclasses (excluding RuntimeException).
25
26
Integer.parseInt (2)
public static int parseInt(String s, int radix) throws NumberFormatException { if (s == null) { throw new NumberFormatException("null"); } if (radix < Character.MIN_RADIX) { throw new NumberFormatException ("radix " + radix + " less than Character.MIN_RADIX"); }
2006, Graham Roberts
Integer.parseInt (3)
For every invalid state detected in the method body an exception is thrown. The method does not attempt to catch its own exceptions. Catching is left to the caller of the method.
Or caller of the caller of the method
27
28
Integer.parseInt (4)
When an exception is thrown the method terminates immediately.
without returning a value in the normal way.
The exception is thrown back to the calling method. The caller method either:
catches the exception. or it terminates immediately and throws the exception back to its caller.
parseInt(String s)
Throw on without catching
Call
f()
Catch and handle
2006, Graham Roberts
29
30
Propagating exceptions
Passing an exception up through a chain of active method calls is called propagation. The active methods calls are those still in progress, leading to the point where the exception occurred.
Uncaught Exceptions
If an exception is passed back to the main method without being caught the program will terminate with an error.
However, program wont compile if exception must be caught.
I.e., subclass of Exception (excl. RuntimeException).
31
32
Stack client
public void aMethod(Stack<String> aStack) { String s; try { s = aStack.pop(); } catch (StackException e) { // Do something to recover // from problem } // ... rest of method }
33
2006, Graham Roberts
or
public void aMethod(Stack<String> aStack) throws StackException { String s = aStack.pop(); // ... rest of method }
The method or a method that calls it must contain the catch block.
34
Issues
Too many exceptions require too many try/catch blocks.
Complicates code. Can reduce readability. Many methods need throws declaration.
A balance is needed.
35
36
Local v. Global
Some local operation (parseInt, open file) may fail.
Deal with problem locally and proceed.
More Information
Read the text book.
37
38
Summary
Exceptions allow errors to be represented and handled in a safe way. Java uses the try, catch & throw mechanism. Throwing an exception forces client code to do something. Dont forget finally.
39