Java Exceptions Dan Fleck CS211

Download Report

Transcript Java Exceptions Dan Fleck CS211

Java Exceptions
Dan Fleck
CS211
What is an Exception

An exception is an event that occurs
during the execution of a program that
disrupts the normal flow of instructions.

Intuition: It’s something you didn’t expect
What happens?

If an exception occurs an “Exception”
object is created, and then passed up the
call stack until someone handles it.
main
Exception
Method 1:
I’ll handle it
Catches
Exception
Method 2:
I can’t
Handle it
Forwards
Call Stack
Exception
I had a
problem
Throws
Catch or Specify

Code that can generate certain
exceptions must either catch or specify it.

Catch:
• try {
… multiple statements …
} catch (SpecificException specificExc) {
… handle exception …
}

Specify:
• public void myMethod() throws SpecificException { … }
Exception Types

Checked exceptions
Must satisfy the catch or specify requirement
 Are subclasses of java.lang.Exception
 Checked exceptions should be handled and
recovered from

• Examples: user types in a bad filename, etc…
Exception Types (cont.)

Unchecked exceptions


Not subject to the catch or specify requirement
Errors - unforeseen error conditions due to external issues that
an application probably cannot recover from.
• Example: IOError when reading a file (due to bad sectors on the
disk)

RuntimeExceptions - error conditions internal to the program
that an application probably cannot recover from.
• Generally these are programming errors or logic errors
• Example: IllegalArgumentException - someone passed in an
invalid argument to your program
Why ever use checked?

You should almost always use checked
exceptions. These exceptions allow a
well-written program to catch and handle
the condition.
Only use unchecked when a reasonable
program cannot deal with the problem.
Catching exceptions

try {
…. Code …
} catch (Exception1 exc) {
} catch (Exception2 exc) {
}
Exceptions
thrown in “code” are caught by the catch blocks.
Catch blocks catch exceptions in order, so put super-classes at
the bottom (catch specific exceptions first)
Example:
} catch (IOException ioe) {
.. Do something specific to an IOException ..
} catch (Exception e) {
.. Catch all other general exceptions and do something for them
}
Finally -- the finally block

try {
….
} catch (Exception e) {
….
} finally {
… Code …
}

The finally block always executes when the try block completes.
This is where you perform any cleanup needed after the try block
completes successfully or throws an exception
Having a finally block is optional -- you don’t need to create one if
you have no cleanup to do, but if you have one it WILL execute
everytime

Altogether now..
public void writeFile(String fileName) {
PrintWriter out = null;
try {
out = new PrintWriter( new FileWriter(fileName));
for (int ind=0; ind < MAX_SIZE; ind++) {
out.println(“Value at “+ind+” is “+vect.elementAt(ind));
}
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("Caught ArrayIndexOutOfBoundsException: “ + e.getMessage());
} catch (IOException ioe) {
System.out.println(“Caught IOException:”+ioe.getMessage());
} finally {
if (out != null) {
out.close();
}
}
Another way: Pass the buck
public void writeFile(String fileName) throws ArrayIndexOutOfBoundsException , IOException {
PrintWriter out = null;
try {
out = new PrintWriter( new FileWriter(fileName));
for (int ind=0; ind < MAX_SIZE; ind++) {
out.println(“Value at “+ind+” is “+vect.elementAt(ind));
}
} finally {
if (out != null) {
out.close();
}
}
NOTE: You can still use the finally block exactly the same!
Now code calling this method must handle the IOException. The code may
optionally handle ArrayIndexOutOfBoundsException since it is a
RuntimeException (unchecked). Which means this method signature is also
valid: public void writeFile(String fileName) throws IOException
How to throw exceptions

Your code may throw exceptions when needed using the throws
keyword. This keyword takes a subclass of Throwable as an
argument (Exceptions/Errors are all subclasses of Throwable)

public void addElement(int index, int[] array, int value) {
if (index >= array.length) {
throw new IllegalArgumentException(
“Array length is:”+array.length+
” and you attempted to add element “+index);
}
array[index] = value;
}

Same rules apply -- if you throw a checked exception it must be
caught or specified.
Writing your own exceptions

You may also create your own exceptions by subclassing
Exception, RuntimeException or Error.

In general you never want to subclass Error and rarely subclass
RuntimeException. You usually create checked exceptions by
subclassing Exception.

public MyException extends Exception {
public MyException(String message) {
super(message);
}
}

Frequently this all you want to do. Occasionally you may add more
features or information to your Exceptions.
Handling Exceptions

Most ways to handle exceptions depend on the
exception type. However, some general
debugging tips are:



Use the printStackTrace() method of exception to
see where the exception occurred
Use getMessage() to show a message to the user
The best exception is one never thrown -- if you can
prevent a user error that would cause an exception
before it happens, do that! (For example, rather than
letting the user type letters into a numeric field,
watch the field and prevent letters from ever going
into the field.)