Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 CS2200 Software Development Lectures 28: Exception Handling A. O’Riordan, 2008 (Includes some slides by Lewis/Loftus 2005 and K. Brown 2004-2007)

Similar presentations


Presentation on theme: "1 CS2200 Software Development Lectures 28: Exception Handling A. O’Riordan, 2008 (Includes some slides by Lewis/Loftus 2005 and K. Brown 2004-2007)"— Presentation transcript:

1 1 CS2200 Software Development Lectures 28: Exception Handling A. O’Riordan, 2008 (Includes some slides by Lewis/Loftus 2005 and K. Brown 2004-2007)

2 2 From "Testing" Lecture: Program Correctness Correctness is an important aspect of software quality. There are a number of different types of errors: ●Lexical error: using words or symbols not in the language ●Syntax error: using words or symbols in the wrong order ●Semantic error: using constructs in a meaningless way ●Run-time error: your code cannot be executed ●Logical error: your program compiles and runs, but doesn't do what it was meant to do Run-time error: your code cannot be executed int values[] = new int[10]; int pos = 20; last = values[pos];

3 3 Problems at Run-time ●some run-time errors are internal to your program, so one option to get rid of them is debugging your code ●Reference null pointer; index out of bounds; division by zero;... ●others arrive from external factors, and cannot be solved by debugging ●communication from an external resource – e.g. a file server or database ●clients (i.e. other programs) are not trustworthy, and supply you with faulty data

4 4 Defensive programming ●your code must take responsibility for protecting itself from receiving bad data or other exceptional run-time situations (e.g. network down, disk full, etc) ●you must anticipate these problems ●your code must detect these problems ●your code must respond to these problems sensibly ●but beware of making your code hard to read and code 'bloat'

5 5 Responding to errors with defaults ●suppose a user types something into a JTextField called tf and you expect them to type a month name...but what if they don't? ●Can validate input public String getMonthFromTF() { String str = tf.getText(); if ( ! isValidMonthName(str)) return "Jan"; else return str; } ●but now the client of the method doesn't know if the user typed "Jan" or rubbish!

6 6 Responding with special values ●or return a special value, e.g. -1, NULL, that signals a problem has occurred: public String getMonthFromTF() { String str = tf.getText(); if (! isValidMonthName(str)) return null; else return str; } Issues: ●special values might not always be available ●will the client remember to check for them?

7 7 Exception Handling I ●Java provides a systematic way of representing, transmitting, capturing and handling well-defined abnormal situations ●when the method detects the abnormal situation, it creates an object called an exception ●And throws the exception, requiring it to be caught and handled by an appropriate exception handler ●This is an abnormal return of the flow of control from the method to the client ●Handling is separated from detecting/throwing, so your code does not get polluted with detailed checks

8 8 Exception Handling II ●Other languages that support exception handling include.NET languages, Ada, Objective-C, and Eiffel ●PL/1 was one of first languages to employ exception handling ●Exception handling mechanism in most popular programming languages is largely similar ●Exception handling is recommended to be used only for signalling/dealing with error conditions and not the normal flow of execution

9 9 Implementation ●In Java exceptions (and errors) are objects ●Exceptions can be raised automatically or explicitly thrown ●Java allows multiple handlers which catch different classes of exceptions ●An alternative is to have a single handling clause which determines the class of exception internally ●finally clause to release resources (executed whether exception occurred or not) ●Terminology varies across languages ●throw or raise; catch or rescue; finally or ensure

10 10 Exceptions and Errors in Java ●An exception is an object that describes an unusual or erroneous situation ●An error is also represented as an object in Java, but usually represents a unrecoverable situation and should not be caught ●Java has a predefined set of exceptions and errors that can occur during execution ●A programmer can also define a new type of exception ●A program can deal with an exception in one of three ways: ●ignore it ●handle it where it occurs ●handle it in another place in the program

11 11 Exception Handling If an exception is ignored by the program, the program will terminate abnormally and produce an appropriate message The message includes a call stack trace that: ●indicates the line on which the exception occurred ●shows the method call trail that lead to the attempted execution of the offending line // generates exception public class Zero { public static void main (String[] args) { int numerator = 1; int denominator = 0; System.out.println (numerator / denominator); System.out.println ("This text will not be printed."); }

12 12 public void method(int arg) { try { //all your normal code goes here //if something goes wrong, Java will "throw" an //Exception, and execution of this block will //stop and we move into the "catch" block } catch (Exception e) { //statement saying what to do if an abnormal //error occurred, and you can get details of //the error from the object reference "e" } Exception Handling: schematic example

13 13 Classes of Exceptions ●Java provides a variety of different classes describing types of exception ●Classes are arranged into a hierarchy with Exception at the top ●Different classes means that the programmer can specify different responses to different types of error ●Wrap the core code inside a try block, and immediately follow it with catch blocks for each type of Exception ●Each catch clause has an associated exception type and is called an exception handler ●When an exception occurs, processing continues at the first catch clause that matches the exception type

14 14 The Exception Class Hierarchy ●Classes that define exceptions are related by inheritance, forming an exception class hierarchy ●All error and exception classes are descendents of the Throwable class ●A programmer can define an exception by extending the Exception class or one of its descendants ● Exception is in the package java.lang ●The parent class used depends on how the new exception will be used

15 Classes of Exceptions Exception CloneNotSupportedException IOException EOFException FileNotFoundException MalformedURLException InterruptedException RuntimeException ("unchecked") IllegalArgumentException NumberFormatException IndexOutOfBoundsException ArrayIndexOutOfBoundsException StringIndexOutOfBoundsException NullPointerException

16 16 IOException Class Operations performed by some I/O classes may throw an IOException because a file might not exist or file exists but program may not be able to find it or the file might not contain the kind of data we expect public class TestData { public static void main (String[] args) throws IOException{ int value =5; FileWriter fw = new FileWriter (test.dat); BufferedWriter bw = new BufferedWriter (fw); PrintWriter outFile = new PrintWriter (bw); for (int line=1; line <= 10; line++) { for (int num=1; num <= 10; num++) { outFile.print (value + " "); } outFile.close(); }

17 17 Example: Integer.parseInt ●suppose you expect the user to type an integer into a JTextField ● parseInt throws a NumberFormatException if the String it is given as input cannot be converted to an int ●the client code should catch and handle the exception: try { String str = tf.getText().trim(); int num = Integer.parseInt(str);... } catch (NumberFormatException nfe) { System.out.println("NOT AN INTEGER!"); }

18 18 The try block and its catch blocks try { some statements to open and read a file } catch (FileNotFoundException fnfe) { state what to do if the file didn't exist } catch (EOFException eofe) { state what to do if EOF encountered unexpectedly } ●try to execute the try block; if no exceptions are thrown, the catch blocks are ignored ●if any statement in the try block throws an exception, the rest of the try block is not executed. Java finds the appropriate catch block, and executes it instead

19 19 the finally block try { some statements } catch (SomeException e) { handle exception } finally { more statements } ●try to execute the try block ●if an exception is thrown, catch and handle it ●Either way, then execute the finally block

20 20 Which catch block is chosen? ●Java looks through the catch clauses one by one and executes the first one it finds that matches (i.e. catches the exception class or a superclass) ●why would this be silly? catch (IOException ioe) { handle the exception } catch (EOFException eofe) { handle the exception }

21 21 What if no catch block matches ●if no catch blocks match, Java tries to pass the exception up the call chain ●if no method in the chain catches it, Java displays an error message on the output window and terminates (except for GUIs) Java runtime system main method calls main method1 calls method1 method2 calls method2 exception if not caught

22 22 Throwing the exception up the chain ●if you anticipate a possible exception being thrown to a method, but you don't want the method to handle it, throw it explicitly in the method signature public void process() throws IOException { ●if you detect an error, and want some calling method to handle it, explicitly throw a new Exception public Object pop() throws EmptyStackException { Object obj; if (size == 0) throw new EmptyStackException();...

23 23 throw Example A throw statement can be executed inside an if statement that evaluates a condition to see if the exception should be thrown The following snippet of code throws a Exception defined below: OutOfRangeException problem = new OutOfRangeException ("Input out of range"); System.out.print ("Enter integer between " + MIN + " and " + MAX); int value = scan.nextInt(); if (value MAX) throw problem; public class OutOfRangeException extends Exception { OutOfRangeException (String message) { super (message); }

24 24 Checked Exceptions ●An exception is either checked or unchecked ●A checked exception either must be caught by a method, or must be listed in the throws clause of any method that may throw or propagate it ●A throws clause is appended to the method header/signature, e.g. void read(String fname) throws IOException, ClassNotFoundException ●The compiler will issue an error if a checked exception is not caught or asserted in a throws clause ●Note that Java is unusual in having checked exceptions (other languages CLU, Modula 3)

25 25 Unchecked Exceptions ●some Exceptions are not required to be caught ●The only unchecked exceptions in Java are objects of type RuntimeException or any of its descendants ●Runtime exceptions could occur in many areas of the code, and requiring that each possible location has a handler will produce inefficient code ●therefore Java allows runtime exceptions to be generated, but does not insist that you catch them


Download ppt "1 CS2200 Software Development Lectures 28: Exception Handling A. O’Riordan, 2008 (Includes some slides by Lewis/Loftus 2005 and K. Brown 2004-2007)"

Similar presentations


Ads by Google