Title: Exceptions: when things go wrong
1Exceptions when things go wrong
2Various sources of error
- Syntactic errors cause problems on compilation
public static doSomething() int i
3.0 while(!done) int i false )
Youve already declared i cant declare it twice!
3Logic errors hard to catch
- Program compiles just fine
- It appears to work
- It just doesn't do what you think it does....
public static double square(double x) return 2
x
But this doesnt square its input it multiplies
it by two.
4Runtime Errors
- Sometimes errors occur at runtime
- e.g. User inputs an empty string when content
is expected - e.g. A divisor turns out to be zero....
- e.g. Array myArray of size X but program refers
to myArrayX (which doesnt exist X-1 is the
last array index) - e.g. A file your program tries to read from
doesnt exist
Runtime Errors generate Exceptions
5Runtime error code
public class myError public static void
main(String args) System.out.println(
3/0)
This program will compile with no errors and will
seem ok. However, this code will produce a
runtime error (and hence an Exception) when it
runs, because you cant divide a number by zero.
6Surviving the crash.........
public static void main(String args) try
System.out.println(3/0) catch
(Exception ex) System.out.println("Erro
r " ex.getMessage())
This trys the statement that might go wrong
(might produce an exception), and catches the
Exception Object ex that is generated if
something does go wrong. The exception object
can then tell us (or the user) what the problem
was.
7A little terminology
- If we try to run some piece of code and something
goes wrong at runtime, an exception is thrown - If the exception is caught by a handler, the
program lives on - If it is not caught, the program dies a grisly
death it crashes.
8Exception is a pre-defined class. When we catch
an exception, we can call methods that tell us
about it e.g ex.getMessage()
RunTimeException
Exception
IOException
Other Exceptions..
Object
Throwable
Error
9- RunTimeExceptions for shame!!!!!!
- These are considered to be your fault.......
ArithmeticException
NullPointerException
RunTimeException
IndexOutOfBoundsException
and others.......
10RuntimeExceptions
- You do not have to catch RuntimeExceptions
- If your code is squeaky clean, these will never
happen - Requires defensive programming (e.g. checking
every value entered by a user) - Commercial-grade code requires an extremely
defensive attitude
11throwing an exception
- If some method you are writing might generate an
exception, you can declare this in advance - You delcare that your method throws and
exception. - Any other code using this method must do
something about the exception must catch that
exception
12Throwing an exception.....
public void myMethod() throws Exception
.... do something dangerous!
Any code calling myMethod must use a try..catch
block
13Catching an Exception
Class userError public static void main(String
args) try myMethod()
catch (Exception e)
System.out.println("Caught this " e)
14Suppose statement2 causes an exception
try statement1 statement2
statement3 catch (Exception e) statement4
Will statement1 be executed? YES Statement2 is
the problem will statement 3 be executed? NO
Statement2 causes an exception. At the
exception
execution jumps to the catch block will statement
4 be executed? YES
15Passing the buck
public void m2() throws Exception // do
something dangerous
Method M1 calls method M2. If M2 throws an
exception to M1, M1 will throw that same
exception onwards.
public void m1()throws Exception // call
m2 m2()
16Exceptions come with Methods
- public String getMessage()
- public String toString()
- public void printStackTrace()
- useful for debugging where did the exception
occur?
17Catching different sorts of exception
- The Class Exception has various different
subclasses (look them up in the API). We can
catch different sorts of exceptions and do
different things in response to them. - try
- myArrayx myArrayx/z
-
- catch(NullPointerException nullPointer)
- System.out.println(myArrayx is empty)
-
- catch(IndexOutOfBoundsException outOfBounds)
System.out.println(myArrayx out of
bounds) -
- catch(ArithmeticException arithmetic)
System.out.println(cant divide by z )
18Finally...........
- If an exception occurs and is not caught, the
method exits immediately - If an exception does not occur, the complete code
of the method is executed - If an exception occurs and is caught, control
passes to the handler, and then continues after
the handler - If a finally clause is provided, along with try
and catch, that code is guaranteed to be
executed, no matter what happens
19try statement1 statement2 catch(Except
ion e) statement3 finally
statement4