Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling...

24
Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws Statement Exception Classes Example: The Debug and AssertionFailure Classes

Transcript of Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling...

Page 1: Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.

Programming and Problem SolvingWith Java

Copyright 1999, James M. Slack

ExceptionsHandling Exceptions with try and catchThe finally-blockThe throws StatementException ClassesExample: The Debug and AssertionFailure Classes

Page 2: Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.

Programming and Problem Solving With Java 2

ExceptionsEasiest way to write a program

Concentrate on main theme of program, ignoring errors and other exceptional conditions

Add error-handling laterIf programming language doesn’t have exceptions

Must intermingle error-handling with main logicMethods need to return special values to signal error

conditionsMakes main logic harder to follow

Page 3: Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.

Programming and Problem Solving With Java 3

ExceptionsExample of error handling without exceptions

sumPositive() method// sumPositive: Returns the sum of the two arguments, or -1// if either argument is not positivestatic int sumPositive(int firstValue, int secondValue){ if (firstValue <= 0 || secondValue <= 0) { return -1; } return firstValue + secondValue;}

How to use the methodint sum = sumPositive(x, y);if (sum == -1){ System.out.println("Error: x or y is < 0");}else{ System.out.println("The sum is " + sum);}

Page 4: Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.

Programming and Problem Solving With Java 4

ExceptionsProblems

Error handling intermingled with main logicint 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 codeint sum = sumPositive(x, y);System.out.println("The sum is " + sum);

May not be a special value that can be an error code

Page 5: Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.

Programming and Problem Solving With Java 5

ExceptionsJava 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 methodtry{ int sum = sumPositive(x, y); System.out.println("The sum is " + sum);}catch (Exception e){ System.out.println(e.getMessage());}

Note main logicis together

Error handlingis here

Page 6: Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.

Programming and Problem Solving With Java 6

ExceptionsProgrammer 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 messageTest.java(21,30) : error J0122: Exception 'Exception' not caught or declared by 'void Test.testSumPositive(int x, int y)'

The method must eitherHandle the exception (using try & catch), orThrow the exception

The method can’t simply ignore the exception

Page 7: Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.

Programming and Problem Solving With Java 7

Exceptions: ThrowingA 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();

// Move off the screen (should throw an exception) myTurtle.move(1000);

// This never executes System.out.println("Program finished"); }}

Exception messageTurtleException: Move offscreen at turtlegraphics.Turtle.move(Compiled Code) at DemoWithoutTryCatch.main(DemoWithoutTryCatch.java:14)

throws clause

Page 8: Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.

Programming and Problem Solving With Java 8

Exceptions: ThrowingCan throw more than one kind of exception from a

methodList them in any orderPut comma between exception names

public static void main(String[] args)throws TurtleException, java.io.IOException{ // Executable code ...}

Page 9: Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.

Programming and Problem Solving With Java 9

Exceptions: HandlingInstead of throwing exception, can handle it in the

methodExample

User enters invalid number Instead of letting program end, catch the exception and

let user re-enter the number

Page 10: Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.

Programming and Problem Solving With Java 10

Exceptions: HandlingCatching 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()); }

System.out.println("Program finished"); }}

Program outputCaught a TurtleException...Message is: Move offscreenValue is: 1000Program finished

trysome code

catchexceptions

Page 11: Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.

Programming and Problem Solving With Java 11

Exceptions: HandlingTry-block

Main code logic that might cause an error (exception)try{ // Move off the screen (should throw an exception) myTurtle.move(1000);}

Catch-blockUse 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 messageSome exceptions have other methods like getValue()

Page 12: Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.

Programming and Problem Solving With Java 12

Exceptions: HandlingCan have several catch-blocks after a try-block

public static void main(String[] args){ Turtle myTurtle = new Turtle(); boolean validDistance;

do { 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");}

Computerchecks

exceptionsin orderlisted

NOTE: List exceptions

from most specific

to most general

Amount to move: 9999Invalid distance - please try againAmount to move: 100Program finished

Page 13: Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.

Programming and Problem Solving With Java 13

Exceptions: PropogatingA method that doesn’t handle (catch) an exception

passes the exception to its caller

Step 1:call A()

Step 2:call B()

Step 3:B() throwsexception

Step 4:A() throwsexception

Step 5:main() throws

exceptionStart

void main() throws XYZException: call A()

void A() throws XYZException: call B()

void B(): throw new XYZException("error")

void main() throws XYZException: call A()

void A() throws XYZException: call B()

void B(): throw new XYZException("error")

Page 14: Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.

Programming and Problem Solving With Java 14

Exceptions: The finally-blockMake computer execute statements no matter what

Put finally-block after last catch-blockStatements 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); } catch (TurtleException e) { System.out.println("Invalid distance"); } catch (java.io.IOException e) { System.out.println("Invalid entry"); } finally { System.out.println("Program finished"); } }

These statementsalways executed

Amount to move: 9999Invalid distanceProgram finished

Amount to move: 100Program finished

Page 15: Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.

Programming and Problem Solving With Java 15

Exceptions: The throws StatementYour 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

Page 16: Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.

Programming and Problem Solving With Java 16

Exceptions: Exception ClassesJava’s predefined hierarchy of exception classes

Object

Throwable

Exception

ArithmeticException NullPointerException IndexOutOfBoundsException ClassCastException EmptyStackException

IOException ParseExceptionClassNotFoundException RuntimeException InterruptedException

Don’t have tocatch or throw

RuntimeExceptionor descendants

Page 17: Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.

Programming and Problem Solving With Java 17

Exceptions: Exception ClassesTo 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); }}

Page 18: Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.

Programming and Problem Solving With Java 18

Exceptions: Exception Classes// Demonstrate the use of MyExemption, a new subclass of Exception

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(); } }}

Exampleof using

newexception

class

3 + 4 is 7Caught a MyException exceptionMessage is: Param(s) to sumPositive < 0

Page 19: Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.

Programming and Problem Solving With Java 19

Exceptions: Exception ClassesCan 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;}

Page 20: Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.

Programming and Problem Solving With Java 20

Exceptions: Exception Classes// Demonstrate the use of MyException2public 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; }

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(); } }}

Use newconstructor

Use newmethod

Exampleof using

newexception

class

Page 21: Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.

Programming and Problem Solving With Java 21

Exceptions: Exception ClassesWhy write exception classes?

Java’s Exception class carries just one stringOther exception classes can include specific information

in the exception objectCan include hints about what caused the error If more than one thing wrong, can include all the

information about what went wrongAlso

Makes program easier to readcatch (EmployeeUnderpaidException e) ...

versuscatch (Exception e) ...

Page 22: Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.

Programming and Problem Solving With Java 22

Example: Debug, AssertionFailureExample of writing and using exception classes:

Debug classAssertionFailure class

Have used these classes in several programsimport 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

Page 23: Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.

Programming and Problem Solving With Java 23

Example: Debug, AssertionFailureUsing 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 exceptionsDisadvantage: can ignore in caller, program then stops

with run-time error

Page 24: Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.

Programming and Problem Solving With Java 24

Example: Debug, AssertionFailureAssertionFailure 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// 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); } }}

Note: subclass ofRunTimeException