Slide6 091101101244 Phpapp01
Slide6 091101101244 Phpapp01
Exceptions
An exception occurs when our code asks the
JVM to perform the technically impossible
and unanticipated (by the compiler)!
Under these circumstances, the JVM
generates an exception. If we dont catch the
exception, the program crashes!
Device Errors:
printer is off/ out of paper
Network is down
Physical limitations:
Disks run out of memory,
quotas fill up,
an infinite recursion causes a stack overflow.
Code errors:
divide by zero,
array out of bound,
integer overflow,
access a null pointer.
Exception Handling
All exception handling has the same goals:
1. Anticipate the error by the user/system
2. Return the program to a safe state that
enables the user to execute other
commands
3. Inform the user of the errors cause
4. Allow the user to save work and terminate
the program gracefully.
Throwable
Error
The Java
Exception
Hierarchy
Exception
IO
Exception
Runtime
Exception
IOException
Trying to read past the end of file
Trying to open a malformed URL
Trying to find a class object for a string
that does not denote an existing class
Methods tell Java their return type, but
also what can go wrong
Public String readLine() throws IOException
RuntimeException caused by
programming error
If its a RuntimeException its your
fault!
Bad cast
Out-of-bounds array access
Null pointer access
Can all be protected against by code
tests.
1.
2.
3.
4.
Also
EOFException e = new
EOFException();
throw e;
Error Messages
Often have a second constructor with a
String
parameter.
String message =
Content-length: + len + received + n;
throw new EOFException(message);
Catching Exceptions
What goes up must come down
Catching exceptions is a bit trickier
Something must catch the exception (see
9.1.1)
An uncaught exception will terminate the
program
print the exception type to screen
print the stack trace.
try/catch block
try
{
mycode
}
catch (ExceptionType e)
{
handler for just this exception type
}
}
catch IOException exception)
{
exception.printStackTrace();
}
}
Exception Information
Exception object may contain error
information
e3.getMessage()
e3.getClass.getName() //returns type
Own defined exception types can place
more information inside constructors.
Exceptions
Objects
Descend from Throwable class
Error message
Program terminates
No program code can prevent
Fault-tolerant
Designed to continue to operate when some part of
system fails
Robustness
Represents degree to which system is resilient to
stress
Segment of code
Immediately follows try block
Handles exception thrown by try block preceding it
Can catch
Object of type Exception
Or Exception child class
throw statement
Sends Exception out of method
It can be handled elsewhere
catch block
Has no return type
Cant call it directly
The MathMistakeCaught
Application
Catch-all block
Unreachable code
Program statements that can never execute
under any circumstances
Format of
try...catch...finally
Sequence
Difficult to follow
Applications purpose and intended outcome lost in
maze of if statements
Coding mistakes because of complicated nesting
Pseudocode Representing
Traditional Error Checking
Unchecked exceptions
Errors
External to program
Runtime exceptions
Internal to program
Logic errors
RuntimeException class
Represent unplanned exceptions that occur
during programs execution
Can occur anywhere in program
Can be numerous in typical program
Checked Exceptions
Must either be caught by a
method or declared in its
signature.
throw
Raises an exception to the first available handler in the call stack,
unwinding the stack along the way.
try
Marks the start of a block associated with a set of exception
handlers.
catch
If the block enclosed by the try generates an exception of this
type, control moves here; watch out for implicit subsumption.
finally
Always called when the try block concludes, and after any
necessary catch handler is complete.
General Syntax
public void setProperty(String p_strValue) throws NullPointerException
{
if (p_strValue == null) { throw new NullPointerException(...); }
}
public void myMethod() {
MyClass oClass = new MyClass();
try {
oClass.setProperty(foo);
oClass.doSomeWork();
} catch (NullPointerException npe) {
System.err.println(Unable to set property: +npe.toString());
} finally {
oClass.cleanup();
}
}
Canonical Example
public void foo() {
try { /* marks the start of a try-catch block */
int a[] = new int[2];
a[4] = 1; /* causes a runtime exception due to the index */
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("exception: " + e.getMessage());
e.printStackTrace();
}
}
/* This code also compiles, but throws an exception at runtime! It
* is both less obvious and more common (an off-by-one-error). */
public int[] bar() {
int a[] = new int[2];
for (int x = 0; x <= 2; x++) { a[x] = 0; }
return a;
}
throw(s) Keyword
/* The IllegalArgumentException is considered unchecked, and
* even making it part of the signature will not alter that. */
public void setName(String p_strName) throws IllegalArgumentException
{
/* valid names cannot be zero length */
if (p_strName.length() == 0) {
throw new IllegalArgumentException();
}
m_strName = p_strName;
}
public void foo() {
setName(); /* No warning about unhandled exceptions. */
}
try Keyword
/* The try statement marks the position of the first bytecode instruction
* protected by an exception handler. */
try {
UserRecord oUser = new UserRecord();
oUser.setName(Fred Stevens);
oUser.store();
/* This catch statement then marks the final bytecode instruction
* protected, and begins the list of exceptions handled. This info
* is collected and is stored in the exception table for the method. */
} catch (CreateException ce) {
System.err.println(Unable to create user record in the database.);
}
catch Keyword
/* A simple use of a catch block is to catch the exception raised by
* the code from a prior slide. */
try {
myObject.setName(foo);
} catch (NuttyParameterException npe) {
System.err.println(Unable to assign name: + npe.toString());
}
try { /* example 2 */
myObject.setName(foo);
} catch (NuttyParameterException npe) { /* log and relay this problem. */
System.err.println(Unable to assign name: + npe.toString());
throw npe;
}
finally Keyword
URL myURL = null;
InputStream oStream = null;
/* The prior sample completely neglected to discard the network
* resources, remember that the GC is non-determinstic!! */
try {
/* Imagine you can see the code from the last slide here... */
} finally { /* What two things can cause a finally block to be missed? */
/* Since we cannot know when the exception occurred, be careful! */
try {
oStream.close();
} catch (Exception e) {
}
}
Steps of trycatchfinally
Every try block must have at least one catch or finally
block attached.
If an exception is raised during a try block: