CMP2004 Advanced Programming: Lecture 6 Exception Handling
CMP2004 Advanced Programming: Lecture 6 Exception Handling
Advanced
Programming
LECTURE 6 EXCEPTION HANDLING
Errors in Programs
Golden rules of Programming
Errors occur in all software programs
try
{
// code that might throw exception
}
catch ([Type of Exception] e) {
// what to do if exception is thrown
}
Handling Multiple Exceptions
Handling multiple possible exceptions by multiple successive catch
blocks
try {
// code that might throw multiple
// exceptions
}
catch (XException e) {
// handle XException
}
catch (YException e2) {
// handle YException
}
Finally Block
The optional finally block at the end of the try-catch block
The finally block provides a mechanism to clean up regardless of what
happens within the try block
Can be used to close files or to release other system resources
Finally Block
try
{
// code that might throw exception
}
catch ([Type of Exception] e) {
// what to do if exception is thrown
}
finally
{
// statements here always get executed
// regardless of code in the try block
}
Checked/Unchecked
Exceptions
Unchecked exceptions or runtime exceptions occur within the JVM
Examples of unchecked exceptions
arithmetic exceptions (dividing by zero)
pointer exceptions (trying to access an object’s members through a null
reference)
indexing exceptions (trying to access an array element with an index that is
too large or too small)
etc.