Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws."— Presentation transcript:

1 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

2 Programming and Problem Solving With Java 2 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

3 Programming and Problem Solving With Java 3 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); }

4 Programming and Problem Solving With Java 4 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

5 Programming and Problem Solving With Java 5 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

6 Programming and Problem Solving With Java 6 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

7 Programming and Problem Solving With Java 7 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(); // 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) throws clause

8 Programming and Problem Solving With Java 8 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... }

9 Programming and Problem Solving With Java 9 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

10 Programming and Problem Solving With Java 10 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()); } System.out.println("Program finished"); }  Program output Caught a TurtleException... Message is: Move offscreen Value is: 1000 Program finished try some code catch exceptions

11 Programming and Problem Solving With Java 11 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()

12 Programming and Problem Solving With Java 12 Exceptions: Handling  Can 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"); } Computer checks exceptions in order listed NOTE: List exceptions from most specific to most general Amount to move: 9999 Invalid distance - please try again Amount to move: 100 Program finished

13 Programming and Problem Solving With Java 13 Exceptions: Propogating  A method that doesn’t handle (catch) an exception passes the exception to its caller

14 Programming and Problem Solving With Java 14 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); } 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 statements always executed Amount to move: 9999 Invalid distance Program finished Amount to move: 100 Program finished

15 Programming and Problem Solving With Java 15 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

16 Programming and Problem Solving With Java 16 Exceptions: Exception Classes  Java’s predefined hierarchy of exception classes Don’t have to catch or throw RuntimeException or descendants

17 Programming and Problem Solving With Java 17 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); }

18 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(); } Example of using new exception class 3 + 4 is 7 Caught a MyException exception Message is: Param(s) to sumPositive < 0

19 Programming and Problem Solving With Java 19 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; }

20 Programming and Problem Solving With Java 20 Exceptions: Exception Classes // 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; } 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 new constructor Use new method Example of using new exception class

21 Programming and Problem Solving With Java 21 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)...

22 Programming and Problem Solving With Java 22 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

23 Programming and Problem Solving With Java 23 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

24 Programming and Problem Solving With Java 24 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 // 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 of RunTimeException


Download ppt "Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws."

Similar presentations


Ads by Google