Transcript Slides
COMP1681 / SE15
Introduction
to Programming
Lecture 27
Exceptions
Today’s Learning Objectives
For you to appreciate why exceptions are a useful
mechanism for signalling errors in programs
For you to understand the effect of exceptions on flow of
control in a program
For you to see how we can intercept exceptions that
occur within Java code
SE15: Exceptions
27–2
Lecture Outline
Traditional approaches to error handling
A different approach: exceptions
Flow of control
Dealing with exceptions
SE15: Exceptions
27–3
Traditional Approaches
To Error Handling
Ignore it!
Terminate the program
Caller should do the right thing
Call System.exit
Transfer responsibility
SE15: Exceptions
27–4
Example: Ignoring Errors
class Date
{
private int day, month, year;
...
public void setMonth(int theMonth)
{
month = theMonth;
}
}
SE15: Exceptions
27–5
Example: Program Termination
class Date
{
private int day, month, year;
...
public void setMonth(int theMonth)
{
if (theMonth < 1 || theMonth > 12) {
System.err.println("Invalid month!");
System.exit(1);
}
month = theMonth;
}
}
SE15: Exceptions
27–6
What Do You Think?
What is wrong with this approach?
Where would it be reasonable to use it?
SE15: Exceptions
27–7
Transfer Responsibility
class Date
{
private int day, month, year;
...
public boolean setMonth(int theMonth)
{
if (theMonth >= 1 && theMonth <= 12) {
month = theMonth;
return true;
}
else
return false;
}
}
SE15: Exceptions
27–8
Dealing With Returned Value
We should do something like this:
do {
String input = JOptionPane.showInputDialog(...);
int month = Integer.parseInt(input);
}
while (! date.setMonth(month));
…but we are allowed to do this:
String input = JOptionPane.showInputDialog(...);
int month = Integer.parseInt(input);
date.setMonth(month);
...
SE15: Exceptions
27–9
Problems
Class author
May not be able to return a boolean from a method
Class user
Other code may ‘swallow up’ the return value
SE15: Exceptions
27–10
The Solution: Exceptions
Build on the idea of transferring error-handling
responsibility to a context better able to deal with it
Not the same as returning an error value
Exceptions change flow of control
Exceptions cannot be ignored
Two aspects
Signalling the error by throwing an exception
Dealing with the error by catching the exception
SE15: Exceptions
27–11
Exceptions in Java
Exceptions are objects, containing
Variables to provide information on the error
Methods to access that information
Two types
Unchecked
ArrayIndexOutOfBoundsException
NullPointerException
NumberFormatException
Checked
FileNotFoundException
SE15: Exceptions
27–12
Flow of Control
After an exception is thrown, normal flow of program
execution is suspended
JVM looks for an exception handler in the method
If there is no handler in the method, the exception moves
up to the caller of the method…
Eventually, exception can end up in main
If main doesn’t handle it, the program is halted
SE15: Exceptions
27–13
Flow of Control
public static void main(String[] args)
{
foo();
…then to here, where it halts program
}
public static void foo()
{
…and propagates to here…
bar();
System.out.println("Foo!");
}
public static void bar()
ArithmeticException
{
occurs here…
int impossibleResult = 1/0;
System.out.println(impossibleResult);
These don’t
}
execute!
SE15: Exceptions
27–14
Dealing With Exceptions
Put code that might throw an exception in a try block
Add one or more catch blocks to match the types of
exception that could be thrown
Write code inside the catch blocks
Print an error message
Log details of error to a file
Fix the problem!
Never ‘swallow’ exceptions
with empty catch blocks!
SE15: Exceptions
27–15
Example
try {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter numerator: ");
int n = keyboard.nextInt();
System.out.print("Enter denominator: ");
int d = keyboard.nextInt();
int result = n/d;
System.out.println("Result = " + result);
}
catch (ArithmeticException error) {
System.err.println("Division by zero!");
}
SE15: Exceptions
27–16
Catching Exceptions in main
Often a good idea
Gives us control of how the program terminates
public static void main(String[] args)
{
try {
Intercepts everything!
...
}
catch (Exception error) {
Prints full details
error.printStackTrace();
//System.err.println(error);
System.exit(1);
}
Prints simple error message
}
SE15: Exceptions
27–17
Summary
We have
Seen that traditional approaches to error handling are
either too inflexible or too easily ignored
Considered how exceptions can solve these problems
Examined how flow of control within a program changes
when an exception is thrown
Looked at examples of Java exceptions
Discussed how to intercept exceptions in Java programs
SE15: Exceptions
27–18