190 likes | 294 Views
06 - Exceptions. A familiar sight?. Bluescreen.scr. … and some more. … and even more . Exceptions. Things go wrong! It's a fact of life! Successful compilation does not guarantee correct behaviour Incorrect downcast of an object Access to a method or field on a null reference.
E N D
A familiar sight? Bluescreen.scr ©S. Uchitel, 2004
… and some more ©S. Uchitel, 2004
… and even more ©S. Uchitel, 2004
Exceptions • Things go wrong! It's a fact of life! • 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 designer you need to anticipate wrong parameters and errors. • The underlying principle is to deal with failures or exceptional circumstances gracefully. ©S. Uchitel, 2004
Exceptions: The user’s perspective 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 ... //Here goes the code, but as user’s we are not interested... ... } • 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... • deal with the exception, or • declare that our method may propagate the exception upwards ©S. Uchitel, 2004
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 Dealing with exceptions public Collection massRegistration(Collection c, Option o) { //Registers students in c, on option o. //Returns students for which registration was unsuccessful Collection failed = new HashSet(); Iterator i = c.iterator(); while (i.hasNext()) { Student s = (Student) i.next(); try { if (!register(s, o)) failed.add(s); } catch (UnknownStudente) { failed.add(s); } } return failed; } ©S. Uchitel, 2004
Propagating Exceptions public Collection massRegistration(Collection c, Option o) throws UnknownStudent { //Registers students in c, on option o. //Returns students for which registration was unsuccessful //Throws exception when if student in c is not an IC student Collection failed = new HashSet(); Iterator i = c.iterator(); while (i.hasNext()) { Student s = (Student) i.next(); if (!register(s, o)) failed.add(s); } 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. ©S. Uchitel, 2004
Dealing with multiple exceptions • Assume: • boolean writeToFile(String s, String content) throws Exception public void writeToFile(String content) throws Exception { String fileName; boolean success = false; while (!success) { System.out.println("Type in a file name."); fileName = InputReader.readString(); try { success = writeToFile(fileName, content); } catch (FileExists e) { System.out.println("File already exists!"); } 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 ©S. Uchitel, 2004
Exceptions: Java syntax summary // For the provider of the method returnType methodName(/* arguments */) throws <exception list> {…} <exception list> = 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 */ } ©S. Uchitel, 2004
Exceptions Are Objects Too • 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. • 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 ©S. Uchitel, 2004
Throwing Exceptions • 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 } ©S. Uchitel, 2004
Using the Exception methods public class ExceptionExample { public static void main(String[] args) { try { exceptionThrower(); } catch (Exception e) { System.out.println(“Found an exception, this is what it said:”); System.out.println(e.getMessage()); System.out.println(“Stack at the time when it was thrown:”); e.printStackTrace(); } } static private void exceptionThrower() throws Exception { throw new Exception(“Hello!”); } } Output? ©S. Uchitel, 2004
Writing Exception classes • This class extends Exception and overrides the getMessage method. public class InvalidFileName extends Exception { public String getMessage() { return "InvalidFileName message (" + super.getMessage()+ ")"; } } ©S. Uchitel, 2004
all other subclasses of Exception are checked NoSuchMethodException Java Exception Class Hierarchy Object Throwable all subclasses of Runtime are unchecked Error Exception IOException RuntimeException ClassCastException FileNotFoundException IndexOutOfBoundsException User Can Define User can Define ©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. • Rarely used. Mostly to terminate programs with customized failure modes. ©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. • 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. ©S. Uchitel, 2004
Exceptions: Summary (1) • Primary means for defensive programming. • Support robust code. • Allow to anticipate the unexpected. • Exceptions are thrown by the called method. • Exception types are declaredin the method signature • 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. ©S. Uchitel, 2004
Exceptions: Summary (2) • 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. ©S. Uchitel, 2004