Presentation is loading. Please wait.

Presentation is loading. Please wait.

06 - Exceptions. 2 ©S. Uchitel, 2004 A familiar sight? Bluescreen.scr.

Similar presentations


Presentation on theme: "06 - Exceptions. 2 ©S. Uchitel, 2004 A familiar sight? Bluescreen.scr."— Presentation transcript:

1 06 - Exceptions

2 2 ©S. Uchitel, 2004 A familiar sight? Bluescreen.scr

3 3 ©S. Uchitel, 2004 … and some more

4 4 ©S. Uchitel, 2004 … and even more

5 5 ©S. Uchitel, 2004 Exceptions Things go wrong! It's a fact of life! Things go wrong! It's a fact of life! Successful compilation does not guarantee correct behaviour Successful compilation does not guarantee correct behaviour  Incorrect downcast of an object  Access to a method or field on a null reference.  A class not present in the classpath As a user of a particular class or method you must prepare to deal with exceptions. As a user of a particular class or method you must prepare to deal with exceptions. As a designer you need to anticipate wrong parameters and errors. As a designer you need to anticipate wrong parameters and errors. The underlying principle is to deal with failures or exceptional circumstances gracefully. The underlying principle is to deal with failures or exceptional circumstances gracefully.

6 6 ©S. Uchitel, 2004 Exceptions: The user’s perspective Method register may terminate... Method register may terminate... ... normally returning a boolean value, or ... abnormally throwing an exception of type StudentUnknown If we want to use the method we must either... If we want to use the method we must either...  deal with the exception, or  declare that our method may propagate the exception upwards public boolean register(Student s, Option o) throws UnknownStudent { //throws exception when Student s is not an IC student //returns false when the student is not registered because the option // is full // is full... //Here goes the code, but as user’s we are not interested......}

7 7 ©S. Uchitel, 2004 Dealing with exceptions public Collection massRegistration(Collection c, Option o) { //Registers students in c, on option o. //Registers students in c, on option o. //Returns students for which registration was unsuccessful //Returns students for which registration was unsuccessful Collection failed = new HashSet(); Collection failed = new HashSet(); Iterator i = c.iterator(); Iterator i = c.iterator(); while (i.hasNext()) { while (i.hasNext()) { Student s = (Student) i.next(); Student s = (Student) i.next(); try { try { if (!register(s, o)) if (!register(s, o)) failed.add(s); failed.add(s); } catch (UnknownStudent e) { catch (UnknownStudent e) { failed.add(s); failed.add(s); } } return failed; return failed;} try this block of code and if any method within it raises an exception go to the catch block if a StudentUnknown exception has happened, execute this block of code

8 8 ©S. Uchitel, 2004 Propagating Exceptions public Collection massRegistration(Collection c, Option o) throws UnknownStudent { //Registers students in c, on option o. //Registers students in c, on option o. //Returns students for which registration was unsuccessful //Returns students for which registration was unsuccessful //Throws exception when if student in c is not an IC student //Throws exception when if student in c is not an IC student Collection failed = new HashSet(); Collection failed = new HashSet(); Iterator i = c.iterator(); Iterator i = c.iterator(); while (i.hasNext()) { while (i.hasNext()) { Student s = (Student) i.next(); Student s = (Student) i.next(); if (!register(s, o)) if (!register(s, o)) failed.add(s); failed.add(s); } return failed; return failed;} This method does not deal with the exception that register may throw. If register throws an exception, massRegistration will stop and propagate it to its own caller.

9 9 ©S. Uchitel, 2004 Dealing with multiple exceptions Assume: Assume: boolean writeToFile(String s, String content) throws Exception boolean writeToFile(String s, String content) throws Exception public void writeToFile(String content) throws Exception { String fileName; String fileName; boolean success = false; while (!success) { System.out.println("Type in a file name."); fileName = InputReader.readString(); try { success = writeToFile(fileName, content); success = writeToFile(fileName, content); } catch (FileExists e) { catch (FileExists e) { System.out.println("File already exists!"); System.out.println("File already exists!"); } catch (InvalidFileName e) { catch (InvalidFileName e) { System.out.println("File name is invalid!"); } }} Deals with only two subclasses of exception, hence must declare that it may raise other exceptions

10 10 ©S. Uchitel, 2004 Exceptions: Java syntax summary // For the provider of the method returnType methodName(/* arguments */) throws {…} = exceptiontype, exceptiontype, … = exceptiontype, exceptiontype, … // when calling a method try { // call the method } catch (ExceptionType name) { … } // any number of catch clauses catch (ExceptionType name) { … } finally { /* code here always gets executed regardless */ }

11 11 ©S. Uchitel, 2004 Exceptions Are Objects Too Like objects exceptions have a type and are instantiated with new. Like objects exceptions have a type and are instantiated with new. Exceptions can be defined with custom structure, operations, constructors, etc. by extending any pre-defined exception type. Exceptions can be defined with custom structure, operations, constructors, etc. by extending any pre-defined exception type. The Exception class is the parent class of all exception classes. The Exception class is the parent class of all exception classes.  Exception();  Exception(String s); // s should be an informational message  getMessage(); // displays informational message  printStackTrace(); //prints to standard error output the stack //of method calls //of method calls

12 12 ©S. Uchitel, 2004 Throwing Exceptions Throwing exceptions is easy. Use the throw keyword Throwing exceptions is easy. Use the throw keyword public boolean register(Student s, Option o) throws UnknownStudent { //throws exception when Student s is not an IC student //returns false when the student is not registered because the option... if (! IC.students.conatins(s)) throw new UnknownStudent(); else... //Check if option o is full }

13 13 ©S. Uchitel, 2004 Using the Exception methods public class ExceptionExample { public static void main(String[] args) { public static void main(String[] args) { try { exceptionThrower(); exceptionThrower();} catch (Exception e) { System.out.println(“Found an exception, this is what it said:”); System.out.println(“Found an exception, this is what it said:”); System.out.println(e.getMessage()); System.out.println(e.getMessage()); System.out.println(“Stack at the time when it was thrown:”); System.out.println(“Stack at the time when it was thrown:”); e.printStackTrace(); e.printStackTrace();} } static private void exceptionThrower() throws Exception { static private void exceptionThrower() throws Exception { throw new Exception(“Hello!”); }} Output?

14 14 ©S. Uchitel, 2004 Writing Exception classes This class extends Exception and overrides the getMessage method. This class extends Exception and overrides the getMessage method. public class InvalidFileName extends Exception { public String getMessage() { return "InvalidFileName message (" + super.getMessage()+ ")"; }}

15 15 ©S. Uchitel, 2004 Java Exception Class Hierarchy Object Throwable Exception IOException IndexOutOfBoundsException NoSuchMethodException RuntimeException User can Define FileNotFoundException User Can Define ClassCastException Error all subclasses of Runtime are unchecked all subclasses of Runtime are unchecked all other subclasses of Exception are checked

16 16 ©S. Uchitel, 2004 The Error throwable class! These represent serious errors, exceptions that applications should not try to catch, e.g., error in the JVM. These represent serious errors, exceptions that applications should not try to catch, e.g., error in the JVM. Rarely used. Mostly to terminate programs with customized failure modes. Rarely used. Mostly to terminate programs with customized failure modes.

17 17 ©S. Uchitel, 2004 Checked and unchecked exceptions Checked exceptions – Declared explicitly in the method signature. The compiler will verify that the exception is either caught or thrown by all calling methods. Checked exceptions – Declared explicitly in the method signature. The compiler will verify that the exception is either caught or thrown by all calling methods. Unchecked exceptions (extend RuntimeException) Unchecked exceptions (extend RuntimeException)  Do not need to be declared in the signature of the method that throws them.  Automatically propagated to the calling context if not caught.  Cause program termination if not caught.

18 18 ©S. Uchitel, 2004 Exceptions: Summary (1) Primary means for defensive programming. Primary means for defensive programming.  Support robust code.  Allow to anticipate the unexpected. Exceptions are thrown by the called method. Exceptions are thrown by the called method. Exception types are declared in the method signature Exception types are declared in the method signature Every exceptions must be either Every exceptions must be either  caught by the calling method and dealt with, or  delcared and propagated to the caller of the calling method. Exceptions are objects, instances of classes. Exceptions are objects, instances of classes.

19 19 ©S. Uchitel, 2004 Exceptions: Summary (2) Catching Exceptions Catching Exceptions  Done according to the exception type  Any number of catch clauses can be specified.  The order in which the catch clauses are matched is the sequential ordering in the java source file.  A catch clause for a supertype will catch all its exception subtypes e.g. catch (Exception e) {…} catches all exceptions  The catch clause for most specific exceptions must be placed before the more general ones.


Download ppt "06 - Exceptions. 2 ©S. Uchitel, 2004 A familiar sight? Bluescreen.scr."

Similar presentations


Ads by Google