You are on page 1of 18

Java Exceptions

1
Intro to Exceptions
Events that occur during the execution of a
program that interrupt the normal flow of
control.
Java provides a general and flexible formalism
for handling Exceptions.

2
Intro to Exceptions
With exception handling,
◦a program can continue executing (rather than terminating)
after dealing with a problem.

◦Robust and fault-tolerant programs


◦ programs that can deal with problems as they arise and continue executing

3
Exception Class hierarchy
Object
•may handle
• must handle
• too serious to catch
Serious system Error
(e.g. ThreadDeath,
OutOfMemoryError)
It’s very unlikely that
the program will be able
to recover, so generally
you should NOT catch
these.

Blue ones represent “Unchecked Exceptions” whereas Pink ones represent “Checked Exceptions” at compile
4 time
Three kinds of Exceptions
There are three different type of exceptions in Java and only
one is subject to catch or specify:
◦ Checked Exceptions: Must handle
◦ Runtime Exceptions: May handle
◦ Errors: May handle
Each of these types is represented by its own class in the
Throwable hierarchy.

5
Exception Handling Basics

Three Claiming exception


ways of
Throwing exception
Exception
handling catching exception

6
Claiming Exceptions
Method declaration must specify every exception that the method
potentially throws
MethodDeclaration throws Exception1, Exception2, ..., ExceptionN

Exceptions themselves are concrete subclasses of Throwable and must


be defined and locatable in regular way.

7
Example of Claiming Exception
import java.io.*;
public class Exception{
public static void main(String[] args) throws FileNotFoundException, IOException
{
InputStream fin;
fin = new FileInputStream("foo.txt");
int input = fin.read();
...

}

8
Throwing Exception
To throw an Exception, use the throw keyword followed by an instance of the
Exception class

void foo() throws SomeException{


if (whatever) {...}
else{ throw new SomeException(...)}

We pass data/msg via the Exception constructor.

Note that if a method foo has a throw clause within it, that the Exception that is
thrown (or one of its superclasses) must be claimed after the signature.

9
Example of throwing Exception
/** Set a new radius */
public void setRadius(double newRadius) throws IllegalArgumentException
{
if (newRadius >= 0)
radius = newRadius;
else
throw new IllegalArgumentException("Radius cannot be negative");
}

10
Catching Exceptions
This is what you will do most try{
commonly. foo();
}
Catching exceptions:
catch(SomeException se){...}
◦ When a method is called that throws
and Exception e.g SomeException, it
must be called in a try-catch block:

11
Catching Exceptions, cont.
Note that if a method throws an Exception that is NOT a
RuntimeException, you must do one of two things:
◦ try-catch it (often called handling it)
◦ rethrow it

In the latter case, responsibility then moves up the calling chain to


handle it, and so on all the way up to main.

12
try-catch Structure
try {
statements; //Statements that may throw exceptions
}
catch (Exception1 exVar1) {
handler for exception1;
At most one
} catch block
catch (Exception2 exVar2) { executes!
handler for exception2;
}
...
catch (ExceptionN exVar3) {
handler for exceptionN;
}

13
Example of Catching Exception
import java.io.*;

public class Exception {


public static void main(String[] args) {
InputStream fin;
try {
fin = new FileInputStream("foo.txt");
int input = fin.read();
} catch (FileNotFoundException fnfe) {
System.out.println(fnfe.getMessage());
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
}
}

14
The Finally Clause
try {
statements; finally block always
} executes once, whether
catch(TheException ex) { there’s an error or not!
handling ex;
}
It’s used generally to
finally {
finalStatements;
release resources (Ex:
} close opened files)

15
Recommendations
Do not use Exceptions to handle normal conditions in the
program that can be checked with if statements. For
example:
◦ to find the end of an array
◦ to check if an object is null

16
Recommendations
try { if (refVar != null)
System.out.println( System.out.println(
refVar.toString());
}
refVar.toString());
catch (NullPointerException ex) { else
System.out.println("refVar is System.out.println("refVar
null"); is null");
}

17
Creating your own Exceptions
You can follow this procedure exactly when creating your own
Exception.

Create a class that extends Exception (or RuntimeException).

You may also add functionality so that a relevant message is stored


when the error is thrown, and any other customized functionality you
choose.

18

You might also like