Transcript An Example

Programming and Problem Solving
With Java
Exceptions
Handling Exceptions with try
and catch
The finally-block
The throws Statement
Exception Classes
Example: The Debug and
AssertionFailure Classes
Copyright 1999, James M. Slack
Exceptions
Easiest way to write a program
Concentrate on main theme of program, ignoring errors
and other exceptional conditions
Add error-handling later
If programming language doesn’t have exceptions
Must intermingle error-handling with main logic
Methods need to return special values to signal error
conditions
Makes main logic harder to follow
Programming and Problem Solving With Java
2
Exceptions
Example of error handling without exceptions
sumPositive() method
// sumPositive: Returns the sum of the two arguments, or -1
//
if either argument is not positive
static int sumPositive(int firstValue, int secondValue)
{
if (firstValue <= 0 || secondValue <= 0)
{
return -1;
}
return firstValue + secondValue;
}
How to use the method
int sum = sumPositive(x, y);
if (sum == -1)
{
System.out.println("Error: x or y is < 0");
}
else
{
System.out.println("The sum is " + sum);
}
Programming and Problem Solving With Java
3
Exceptions
Problems
Error handling intermingled with main logic
int sum = sumPositive(x, y);
if (sum == -1)
{
System.out.println("Error: x or y is < 0");
}
else
{
System.out.println("The sum is " + sum);
}
Programmers can ignore the error code
int sum = sumPositive(x, y);
System.out.println("The sum is " + sum);
May not be a special value that can be an error code
Programming and Problem Solving With Java
4
Exceptions
Java has exceptions
sumPositive() method now throws an exception
// sumPositive: Returns the sum of the two arguments. Throws
//
Exception if either argument is less than
//
zero.
public static int sumPositive(int first, int second)
throws Exception
{
if (first < 0 || second < 0)
{
throw new Exception("Param(s) to sumPositive < 0");
}
}
return first + second;
How to use the method
try
{
int sum = sumPositive(x, y);
System.out.println("The sum is " + sum);
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
Note main logic
is together
Error handling
is here
Programming and Problem Solving With Java
5
Exceptions
Programmer can’t ignore exceptions
// testSumPositive: Show that programmer can't ignore exception
//
thrown from sumPositive()
public static void testSumPositive(int x, int y)
{
int sum = sumPositive(x, y);
System.out.println("The sum is " + sum);
}
Compiler gives error message
Test.java(21,30) : error J0122: Exception 'Exception' not caught or
declared by 'void Test.testSumPositive(int x, int y)'
The method must either
Handle the exception (using try & catch), or
Throw the exception
The method can’t simply ignore the exception
Programming and Problem Solving With Java
6
Exceptions: Throwing
A method can throw an exception
Include a throws clause as part of the method’s signature
// Demonstration of a program that throws a TurtleException
import turtlegraphics.*;
public class DemoWithoutTryCatch
{
public static void main(String[] args)
throws TurtleException
{
Turtle myTurtle = new Turtle();
throws clause
// Move off the screen (should throw an exception)
myTurtle.move(1000);
}
}
// This never executes
System.out.println("Program finished");
Exception message
TurtleException: Move offscreen
at turtlegraphics.Turtle.move(Compiled Code)
at DemoWithoutTryCatch.main(DemoWithoutTryCatch.java:14)
Programming and Problem Solving With Java
7
Exceptions: Throwing
Can throw more than one kind of exception from a
method
List them in any order
Put comma between exception names
public static void main(String[] args)
throws TurtleException, java.io.IOException
{
// Executable code ...
}
Programming and Problem Solving With Java
8
Exceptions: Handling
Instead of throwing exception, can handle it in the
method
Example
User enters invalid number
Instead of letting program end, catch the exception and
let user re-enter the number
Programming and Problem Solving With Java
9
Exceptions: Handling
Catching an exception with try-catch
// Demonstration of how to catch an exception
import turtlegraphics.*;
public class DemoCatchException
{
public static void main(String[] args)
{
Turtle myTurtle = new Turtle();
try
{
// Move off the screen (should throw an exception)
myTurtle.move(1000);
}
catch (TurtleException e)
{
System.out.println("Caught a TurtleException...");
System.out.println("Message is: " + e.getMessage());
System.out.println("Value is: " + e.getValue());
}
}
}
try
some code
catch
exceptions
System.out.println("Program finished");
Program output
Caught a TurtleException...
Message is: Move offscreen
Value is: 1000
Program finished
Programming and Problem Solving With Java
10
Exceptions: Handling
Try-block
Main code logic that might cause an error (exception)
try
{
// Move off the screen (should throw an exception)
myTurtle.move(1000);
}
Catch-block
Use for error handling
catch (TurtleException e)
{
System.out.println("Caught a TurtleException...");
System.out.println("Message is: " + e.getMessage());
System.out.println("Value is: " + e.getValue());
}
Exception is an object (e in this example)
Use e.getMessage() to get exception’s message
Some exceptions have other methods like getValue()
Programming and Problem Solving With Java
11
Exceptions: Handling
Can have several catch-blocks after a try-block
Computer
checks
exceptions
in order
listed
public static void main(String[] args)
{
Turtle myTurtle = new Turtle();
Amount to move: 9999
boolean validDistance;
Invalid distance - please try again
do
Amount to move: 100
{
Program finished
validDistance = true;
try
{
int distance = Keyboard.readInt("Amount to move: ");
myTurtle.move(distance);
}
catch (TurtleException e)
{
System.out.println("Invalid distance - please try again");
validDistance = false;
}
catch (java.io.IOException e)
{
System.out.println("Invalid entry - please try again");
validDistance = false;
}
} while (!validDistance);
}
System.out.println("Program finished");
Programming and Problem Solving With Java
12
Exceptions: Propogating
A method that doesn’t handle (catch) an exception
passes the exception to its caller
Step 5:
main() throws
exception
Start
void main() throws XYZException:
call A()
Step 1:
call A()
void A() throws XYZException:
call B()
Step 2:
call B()
void B():
throw new XYZException("error")
Programming and Problem Solving With Java
void main() throws XYZException:
call A()
Step 4:
A() throws
exception
void A() throws XYZException:
call B()
Step 3:
B() throws
exception
void B():
throw new XYZException("error")
13
Exceptions: The finally-block
Make computer execute statements no matter what
Put finally-block after last catch-block
Statements execute whether exception caught or not
public static void main(String[] args)
{
Turtle myTurtle = new Turtle();
}
try
{
int distance = Keyboard.readInt("Amount to move: ");
myTurtle.move(distance);
}
Amount to move: 9999
catch (TurtleException e)
Invalid distance
{
Program finished
System.out.println("Invalid distance");
}
catch (java.io.IOException e)
Amount to move: 100
{
System.out.println("Invalid entry");
Program finished
}
finally
{
System.out.println("Program finished");
}
Programming and Problem Solving With Java
These statements
always executed
14
Exceptions: The throws Statement
Your methods can throw exceptions
Good for methods with preconditions -- throw exception if
precondition not met
Calling method can then decide what to do
// sumPositive: Returns the sum of the two arguments. Throws
//
Exception if either argument is less than
//
zero.
public static int sumPositive(int first, int second)
throws Exception
{
if (first < 0 || second < 0)
{
throw new Exception("Param(s) to sumPositive < 0");
}
}
return first + second;
Any method that uses sumPositive() must catch or throw
Exception
Programming and Problem Solving With Java
15
Exceptions: Exception Classes
Java’s predefined hierarchy of exception classes
Obj ect
Throwable
Exception
ClassNotFoundException
ArithmeticException
IOException
NullPointerException
Programming and Problem Solving With Java
RuntimeException
IndexOutOfBoundsException
Don’t have to
catch or throw
RuntimeException
or descendants
InterruptedException
ClassCastException
ParseException
EmptyStackException
16
Exceptions: Exception Classes
To write your own exception class
Extend the Exception class (usually)
Can provide constructors and other methods
// Simple exception class that does nothing more than Exception
public class MyException extends Exception
{
// Default constructor
public MyException() {}
}
// Constructor with message
public MyException(String message)
{
super(message);
}
Programming and Problem Solving With Java
17
Exceptions: Exception Classes
// Demonstrate the use of MyExemption, a new subclass of Exception
Example
of using
new
exception
class
public class MyExceptionDemo
{
// sumPositive: Returns the sum of the two arguments. Throws
//
MyException if either argument is less than zero.
public static int sumPositive(int first, int second)
throws MyException
{
if (first < 0 || second < 0)
{
throw new MyException("Param(s) to sumPositive < 0");
}
return first + second;
}
public static void main(String[] args)
throws java.io.IOException
{
try
{
// First use of sumPositive() should work
System.out.println("3 + 4 is " + sumPositive(3, 4));
// Second use should fail
System.out.println("3 + (-4) is " + sumPositive(3, -4));
}
}
}
catch (MyException e)
{
System.out.println("Caught a MyException exception");
System.out.println("Message is: " + e.getMessage());
System.in.read();
}
Programming and Problem Solving With Java
3 + 4 is 7
Caught a MyException exception
Message is: Param(s) to sumPositive < 0
18
Exceptions: Exception Classes
Can add methods to your exception class that are
application-specific
// This exception class stores a single integer for
// information about the error.
public class MyException2 extends Exception
{
// Constructor with message
public MyException2(String message, int badValue)
{
super(message);
this.badValue = badValue;
}
// getBadValue: Returns the value that caused the problem
public int getBadValue()
{
return badValue;
}
}
// Instance variables
int badValue;
Programming and Problem Solving With Java
19
Exceptions: Exception Classes
Example
of using
new
exception
class
// Demonstrate the use of MyException2
public class MyException2Demo
{
// sumPositive: Returns the sum of the two arguments. Throws
//
MyException if either argument is less than zero.
public static int sumPositive(int first, int second)
throws MyException2
{
if (first < 0 || second < 0)
{
throw new MyException2("Param(s) to sumPositive < 0",
Math.min(first, second));
}
}
return first + second;
Use new
constructor
public static void main(String[] args)
throws java.io.IOException
{
try
{
// First use of sumPositive() should work
System.out.println("3 + 4 is " + sumPositive(3, 4));
// Second use should fail
System.out.println("3 + (-4) is " + sumPositive(3, -4));
}
}
catch (MyException2 e)
{
System.out.println("Caught a MyException exception");
System.out.println("Message is: " + e.getMessage());
System.out.println("Bad value is: " + e.getBadValue());
System.in.read();
}
Programming}and Problem Solving With Java
Use new
method
20
Exceptions: Exception Classes
Why write exception classes?
Java’s Exception class carries just one string
Other exception classes can include specific information
in the exception object
Can include hints about what caused the error
If more than one thing wrong, can include all the
information about what went wrong
Also
Makes program easier to read
catch (EmployeeUnderpaidException e) ...
versus
catch (Exception e) ...
Programming and Problem Solving With Java
21
Example: Debug, AssertionFailure
Example of writing and using exception classes:
Debug class
AssertionFailure class
Have used these classes in several programs
import Debug;
...
// (Don’t need to import AssertionFailure)
// sumPositive: Returns the sum of the two arguments.
public static int sumPositive(int first, int second)
{
Debug.assert(first >= 0 && second >= 0,
"sumPositive(): bad arguments");
return first + second;
}
Use of Debug.assert()
Debug.assert(condition, message);
If condition is false, assert() throws AssertionFailure
exception
Programming and Problem Solving With Java
22
Example: Debug, AssertionFailure
Using Debug.assert() is alternative to exceptions
Can use to make sure program is running correctly,
without overhead of throwing exceptions
Advantage: easier to use than exceptions
Disadvantage: can ignore in caller, program then stops
with run-time error
Programming and Problem Solving With Java
23
Example: Debug, AssertionFailure
AssertionFailure class
// AssertionFailure, a subclass of RuntimeException
// (so this exception does not need to be caught or thrown)
public class AssertionFailure extends RuntimeException
{
// Constructor
public AssertionFailure(String message)
{
super(message);
}
}
Debug class
Note: subclass of
RunTimeException
// The Debug class, which contains the assert() method
public class Debug
{
// assert: Raises an AssertionFailure exception if the condition
//
is false
public static void assert(boolean condition, String message)
throws AssertionFailure
{
if (!condition)
{
throw new AssertionFailure(message);
}
}
}
Programming and Problem Solving With Java
24