1 / 23

Principles of Programming II

Principles of Programming II. Exceptions. Chapter Objectives. Understand how exceptions work in Java Know how to use try-catch syntax Be able to pass exceptions up the call stack. Opening files. Consider the following code: //create the file object

steffi
Download Presentation

Principles of Programming II

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Principles of Programming II Exceptions

  2. Chapter Objectives • Understand how exceptions work in Java • Know how to use try-catch syntax • Be able to pass exceptions up the call stack

  3. Opening files • Consider the following code: //create the file object FileReader file = new FileReader("dataFile.txt"); //create a Scanner object for the file Scanner dataIn = new Scanner(file); • What problems can occur? • File is not there

  4. Exception Handling • Errors represent unrecoverable situations. • Exceptions are similar, but programmer can: • Not handle the exception • Leads to abnormal termination with error messages • Handle the error where it occurs (where it is “thrown”) • Use try-catch statement • Handle the exception at another point in the program • Propagates upward (calling method, its calling method, etc.)

  5. Examples of Java Exceptions • ArithmaticException • Illegal operation such as divide by 0 • ArrayIndexOutOfBoundsException • An array index is outside the array • EOFException • Premature end of file encountered

  6. References • http://pages.cs.wisc.edu/~hasti/cs368/JavaTutorial/NOTES/Exceptions.html • A list of exceptions and some simple examples are available at: http://mindprod.com/jgloss/exception.html

  7. Try-Catch Statement • The try statement identifies a block of code that may throw an exception • A block of code may throw more than one exception • The catch clause defines how the associated exception should be handled • A try block may have multiple catch clauses • Each catch block would handle a different exception • The finally clause executes after the try and any catch blocks • The finally clause is most often used to manage resources • A finally block executes whether or not an exception occurs • NOTE: a try block does not have to have either catch OR finally clauses

  8. Flow of control • The code inside the try block is executed • If no exception is thrown, the code following the catch blocks is executed. • If an exception is thrown, control is transferred to the first catch handler whose exception corresponds to the one thrown • Whether or not an exception is thrown, control is then passed to the finally block if it is defined

  9. Flow of control try { in = new FileInputStream(file); return readDataSet(in); }catch (IOExceptione) { throw new BadDataSetException(); } finally { in.close(); } // other Java code 1. Execute code 2. If an exception is raised by some line in the try block, go here 3. Always do this code 4. After the “finally” block, jump here if there is no exception.

  10. Example String ID = “12345678987654321”; try { //ID is a String code = ID.charAt(9); String myInt = ID.substring(3,7); System.out.println(myInt); num = Integer.parseInt(myInt); num++; System.out.println(“num is “ + num); } catch (StringIndexOutOfBoundsException exception) { System.out.println ("Improper ID length: " + ID); } catch (NumberFormatException exception) { System.out.println (“ID number value is not numeric: " + ID); }

  11. Example • In the statement: catch (StringIndexOutOfBoundsException exception) • The variable exception in the catch block is a parameter used to hold the exception object that is returned when an exception is thrown

  12. User Exceptions • You can create your own exceptions • Must extend the Throwable class • Most are derived from the Exception class (a subclass of Throwable) • Must throw a checked exception to propagate it up the call stack

  13. Using Exceptions • Class must declare all checked exceptions that it throws • Unchecked exceptions represent logic errors in the code; you cannot predict these • RuntimeException, Error or subclasses of these • Unchecked exceptions can be thrown anywhere • Checked exceptions represent conditions that can reasonably be expected to occur • E.g., IOException • Must declare these if throw them

  14. Checked exceptions • If you invoke a method that lists a checked exception in its throws clause you have 3 choices: • Catch the exception and handle it • Catch the exception and map it into one of your exceptions • i.e., throw an exception of a type declared in your own throws clause • Declare the exception in your throws clause and let the exception past through your method

  15. Checked exceptions: option 1 • Catch the exception and handle it try { //ID is a String code = ID.charAt(9); num = Integer.parseInt(ID.substring(3, 7)); } catch (StringIndexOutOfBoundsException exception) { System.out.println ("Improper ID length: " + ID); }

  16. Checked exceptions • Catch the exception and map it into one of your exceptions • I.e., throw an exception of a type declared in your own throws clause public double[] getDataSet(String setName) throws BadDataSetException try { //ID is a String code = ID.charAt(9); num = Integer.parseInt(ID.substring(3, 7)); } catch (StringIndexOutOfBoundsException exception) { throw new BadDataSetException(); } }

  17. Checked exceptions • Declare the exception in your throws clause and let the exception pass through your method public double[] getDataSet(String setName) throws StringIndexOutOfBoundsException, NumberFormatException // note that we must throw every type of exception that we could get for this to work { // don’t need to catch, will throw automatically code = ID.charAt(9); num = Integer.parseInt(ID.substring(3, 7)); }

  18. Example Class BadDataSetExcption extends Exception{} Class MyUtilities { public double[] getDataSet(String setName) throws BadDataSetException { String file = setName + “.dset”; FileInputStream in = null; try { in = new FileInputStream(file); return readDataSet(in); } catch (IOException e) { throw new BadDataSetException(); } finally { try { if (in != null) in.close(); } catch (IOException e){ ; // ignore: we successfully read the data } }}

  19. Exception Propagation • An exception may be handled at other levels • If an exception is thrown and not handled, the exception (and control) is passed to the calling method • If not handled there, it is passed to that method’s calling method and so on. • To handle the exception in the calling block, the call to the method that throws the exception must be inside a try-catch block

  20. Exception Propagation • Almost all exceptions in Java are “checked” exceptions • Must be caught by the method OR listed in a throws clause in the method header in order to be propagated.

  21. File I/O • How do you know which classes/methods have “checked” exceptions? • Look at the JavaDoc online • Example: FileReader • Go to the javadoc for FileReader • Look at the constructor that you want to use • Look at the last line in the method description that says “Throws:” • You must catch or throw any exception listed.

  22. Opening a file One way to handle the FileNotFoundException is for our method to throw it also. public static void main(String[] args) throws FileNotFoundException { FileReader file = new FileReader("dataFile.txt"); //create the file object Scanner dataIn = new Scanner(file); //create a Scanner object for the file String name; double hours, rate, pay; while (dataIn.hasNext()){ name=dataIn.next(); hours = dataIn.nextDouble(); rate = dataIn.nextDouble(); pay = hours * rate; System.out.println(name + " should be paid $" + pay); } } This throws a FileNotFoundExceptionaccording to the JavaDoc

  23. Opening a file public static void main(String[] args) { try{ FileReader file = new FileReader("dataFile.txt"); //create the file object Scanner dataIn = new Scanner(file); //create a Scanner object for the file String name; double hours, rate, pay; while (dataIn.hasNext()){ name=dataIn.next(); hours = dataIn.nextDouble(); rate = dataIn.nextDouble(); pay = hours * rate; System.out.println(name + " should be paid $" + pay); } } catch (FileNotFoundException e) { System.out.println(“Could not open dataFile.txt”); } } This throws a FileNotFoundExceptionaccording to the JavaDoc Or we can catch the exception and handle it ourselves.

More Related