CMP2004
Advanced
Programming
LECTURE 6 EXCEPTION HANDLING
Errors in Programs
Golden rules of Programming
Errors occur in all software programs
How to deal with errors
Try to minimize their occurrence (bug checking)
Data validation (prevent invalid data)
Handle them as they occur
Errors can be dealt with at place error occurs
Easy to see if proper error checking implemented
Harder to read application itself and see how code works
Error handling (old way)
if (file exists) {
open file;
while (there is more records to be processed) {
if (no IO errors) {
process the file record
}
else {
handle the errors
}
}
if (file is opened)
close the file;
}
else {
report the file does not exist;
}
Sample Code
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter an integer numerator: ");
int numerator = scanner.nextInt();
System.out.print("Please enter an integer denominator: ");
int denominator = scanner.nextInt();
int result = numerator / denominator;
System.out.printf("Result: %d / %d = %d%n", numerator, denominator,
result);
}
Output
Output
Output
Sample Code (Fix it)
...
int denominator = scanner.nextInt();
if(denominator!=0) {
int result = numerator / denominator;
System.out.printf("%nResult: %d / %d = %d%n",
numerator, denominator,
result);
}
else {
System.out.print("denominator must be nonzero ");
}
...
What is an Exception?
Definition: An exception or exceptional event is an event that occurs
during the execution of a program that disrupts the normal flow of
instructions
The following will cause exceptions
Accessing an out-of-bounds array element
Writing into a read-only file
Trying to read beyond the end of a file
Sending illegal arguments to a method
Performing illegal arithmetic (e.g divide by 0)
Hardware failures…
Exception Terminology
When an exception occurs, we say it was thrown or raised
When an exception is dealt with, we say it is handled or caught
The block of code that deals with exceptions is known as an exception
handler
Exception Handling
Makes clear, robust, fault-tolerant programs
Separates error handling code from "main line" of program
Deals with synchronous errors (i.e., Divide by zero)
Used when system can recover from error
Exception handler(recovery procedure)
Typically used when error dealt with in different place than where it occurred
Exception Rules in JAVA
1. Exceptions must be Declared
public void methodReadFile(File source) throws FileNotFoundException;
2. Exceptions must be Handled
try {
methodReadFile (new File("test.in"));
// do something if no exception ...
// you main logic here in the try-block
} catch (FileNotFoundException ex) {
// error handling separated from the main logic
}
Exception Handling
Operations
Java’s exception handling consists of three operations:
Declaring exceptions;
Throwing an exception; and
Catching an exception.
Declaring exceptions
A Java method must declare in its signature the types of exception it
may "throw" from its body, via the keyword "throws"
public void methodD() throws XException, YException
{
// method body throw XException and YException
}
Throwing an Exception
In case of an error create an appropriate Exception object and throw it
public void methodD() throws XException, YException { // method's signature
// method's body
...
...
// XException occurs
if ( ... )
throw new XException(...); // construct an XException object and
throw
...
// YException occurs
if ( ... )
throw new YException(...); // construct an YException object and
throw
...
}
Throwing an Exception
The throw statement requires a single argument: a throwable object
Throwable objects are instances of any subclass of the Throwable class
Include all types of errors and exceptions
Check the API for a full listing of throwable objects
Catching an Exception
try-catch block:
Enclose code that may generate an error in try block
Follow with one or more catch blocks
Each catch block has an exception handler
If exception occurs and matches parameter in catch block, code in catch
block executed
If no exception thrown, exception handlers skipped and control resumes
after catch blocks
Format
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.
A method does not have to catch or specify that it throws unchecked
exceptions, although it may
Checked/Unchecked
Exceptions
Checked exceptions or compile time exceptions exceptions that occur
in
code outside of the Java runtime system
For example, exceptions that occur during I/O (covered next lecture)
are
checked exceptions
The compiler ensures that checked exceptions are caught or are
specified
to be thrown (using the throws keyword)
Handling Checked Exceptions
Every method must catch checked exceptions OR specify that it
may throw them (using the throws keyword)
Handling Checked Exceptions
void readFile(String filename) {
try {
FileReader reader = new FileReader("myfile.txt");
// read from file . . .
} catch (FileNotFoundException e) {
System.out.println("file was not found");
}
}
void readFile(String filename) throws FileNotFoundException {
FileReader reader = new FileReader("myfile.txt");
// read from file . . .
}
Writing Your Own Exceptions
There are at least 2 types of exception constructors:
Default constructor: No arguments
NullPointerException e = new NullPointerException();
Constructor that has a detailed message: Has a single String argument
IllegalArgumentExceptione e =
new IllegalArgumentException("Number must be positive");
Writing Your Own Exceptions
Your own exceptions must be a subclass of the Exception class and have
at least the two standard constructors
public class MyCheckedException extends IOException {
public MyCheckedException() { }
public MyCheckedException(String m) {
super(m);
}
}
public class MyUncheckedException extends RuntimeException {
public MyUncheckedException() {}
public MyUncheckedException(String m) {
super(m);
}
}