Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Exception.

Slides:



Advertisements
Similar presentations
Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 14: Stepwise.
Advertisements

Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 0: Introduction.
Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.
Yoshi
Lecture 9. 2 Exception  An exception is a unusual, often unpredictable event, detectable by software or hardware, that requires special processing occurring.
An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
Chapter 16: Exception Handling C++ Programming: From Problem Analysis to Program Design, Fifth Edition.
Objectives In this chapter you will: Learn what an exception is Learn how to handle exceptions within a program See how a try / catch block is used to.
Exceptions Any number of exceptional circumstances may arise during program execution that cause trouble import java.io.*; class IOExample { public static.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
CSI 3120, Exception handling, page 1 Exception and Event Handling Credits Robert W. Sebesta, Concepts of Programming Languages, 8 th ed., 2007 Dr. Nathalie.
Lecture 27 Exceptions COMP1681 / SE15 Introduction to Programming.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
Exceptions Used to signal errors or unexpected situations to calling code Should not be used for problems that can be dealt with reasonably within local.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
Java Review 2 – Errors, Exceptions, Debugging Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Introduction to Java Chapter 11 Error Handling. Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle.
Chapter 1: Introduction To Computer | SCP1103 Programming Technique C | Jumail, FSKSM, UTM, 2005 | Last Updated: July 2005 Slide 1 Introduction To Computers.
1 Exception and Event Handling (Based on:Concepts of Programming Languages, 8 th edition, by Robert W. Sebesta, 2007)
Exceptions COMPSCI 105 S Principles of Computer Science.
© Janice Regan, CMPT 128, Jan CMPT 128 Introduction to Computing Science for Engineering Students Creating a program.
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
UNIT 3 TEMPLATE AND EXCEPTION HANDLING. Introduction  Program errors are also referred to as program bugs.  A C program may have one or more of four.
Basics Programming Concepts. Basics A computer program is a set of instructions to tell a computer what to do Machine language = circuit level language.
Coding Methodology How to Design Code. © 2005 MIT-Africa Internet Technology Initiative Pay Attention to Detail When implementing or using APIs details.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
1 Problem Solving with C++ The Object of Programming Walter Savitch Chapter 1 Introduction to Computers and C++ Programming Slides by David B. Teague,
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
WEEK 2 Introduction to Java II CSE 252 Principles of Programming Languages LAB SECTION.
School of Computer Science & Information Technology G6DICP - Lecture 6 Errors, bugs and debugging.
Chapter 15: Exception Handling C++ Programming: Program Design Including Data Structures, Fifth Edition.
Error Handling Tonga Institute of Higher Education.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Exception Handling How to handle the runtime errors.
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Exceptions an unusual condition – e.g. division by zero – e.g. file doesn't exist – e.g. illegal type – etc. etc… typically a run-time error – i.e. during.
1 Handling Errors and Exceptions Chapter 6. 2 Objectives You will be able to: 1. Use the try, catch, and finally statements to handle exceptions. 2. Raise.
Garbage Collection It Is A Way To Destroy The Unused Objects. To do so, we were using free() function in C language and delete() in C++. But, in java it.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
Eighth Lecture Exception Handling in Java
Dept of Computer Science University of Maryland College Park
14 Compilers, Interpreters and Debuggers
Exceptions In this lecture:
Tirgul 13 Exceptions 1.
CS1101X Programming Methodology
Testing and Debugging.
Introduction to Exceptions in Java
Testing and Exceptions
Chapter 14: Exception Handling
Exceptions 10-Nov-18.
Exception Handling Chapter 9.
Exceptions Problems in a Java program may cause exceptions or errors representing unusual or invalid processing. An exception is an object that defines.
Algorithm Correctness
Exception Handling Imran Rashid CTO at ManiWeber Technologies.
Exceptions 10-May-19.
Lecture 9.
Java Basics Exception Handling.
Error Handling in Java Servlets
CMSC 202 Exceptions.
Presentation transcript:

Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Exception Handling Prof. Dr. Max Mühlhäuser Dr. Guido Rößling

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Overview Errors and their classification Error handling without language support and its problems Basics of error handling with language support in Java Advantages of error handling with language support in Java Summary 2

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Lexical errors: Wrong or unknown words are used in program code //... int[] result = neu int[5]; result.size(); //... Syntax errors: Wrong order of the words in program statements... move(); public static void main(String[] args) { new Robot(0, 1, 0, North); }... Classification of errors 3 Lexical and syntactical errors are discovered and signaled by the compiler

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Classification of errors 4 Run-time errors –Any extraordinary event that occurs during program execution and disturbs the ordinary control flow  error termination Division by 0 A non-existing graphical object shall be painted Intention errors –Program runs normally, but returns wrong results

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Error Handling, Bugs and Debugging 5 Dealing with errors is an important part of software development: Quality assurance! The usual reaction to untreated exceptions is a program crash –This may be better than incorrect results that remain unnoticed for a long time Complex programs and distributed applications without any provision for handling exceptions are inacceptable –Telecommunication systems –Guidance and control systems, e.g., for rockets or nuclear plants Programs that treat errors gracefully are called robust

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Error Handling, Bugs and Debugging 6 This lecture  catching and resolving runtime errors –Heavy-weigth vs. light-weight errors Next lecture  Intention errors: test or verify that the software does what it is supposed to do Bug: name for all types of all program errors –Origin: A dead moth (not really a “bug”) in a relais caused a malfunction. –Usually hard to find, „100% bug free“ is close to impossible Debugging = searching for errors Both words go back to Grace Hopper

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Heavyweight runtime errors Two types of heavyweight programming errors: –System faults: faults in the Java VM, lack of free memory, … Not the application programmer’s fault Cannot be caught and lead directly to a program crash Programming faults after which a continuation is not possible –A required class is not available 7

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Lightweight errors Lightweight errors (also called exceptions) are errors which can be caught in the program; continuing the program is possible after fixing the error problem: input of a wrong file name by the user solution: repeat input problem: wrong data in a file that can be ignored, e.g., uninterpretable image or audio signal solution: Ignore the data problem: network connection crashes solution: reconnect 8

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Some typical exceptions 9 Access to a method or instance variable of a non-existing object (null) Effectively there was an attempt to access "null.name" The existence of the object should be checked before access! public void printPerson() { Person aPerson = null; printName(aPerson); // … } public void printName(Person p) { System.out.println(p.name); } Problem: sending a message to "null" Result: NullPointerException

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Some typical exceptions 10 int[] matriculationNumber = new int[27]; for (int i = 0; i <= 27; i++) System.out.println(matriculationNumber[i]); Problem: illegal array access with i == 27 Result: ArrayIndexOutOfBoundsException Only positions i with 0 <= i < array.length are valid Especially tricky is the case of call parameters Always test how many arguments were passed (args.length)

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Some typical exceptions public static void main(String[] args) { int count; count = Integer.parseInt(args[1]); //... } 11 Problem 2: Attempt to parse a non-number if args[1] is e.g., "Hello". Text cannot be transformed into a number Result 2: NumberFormatException Problem 1: illegal array access if no parameters were passed to the program. In this case, args has no elements - accessing args[1] fails Result 1: ArrayIndexOutOfBoundsException code carries potential for multiple errors!

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Exception handling Exception handling can be done… –without language support In languages such as C or Pascal –with language support In languages such as Ada, Smalltalk, Java In the following, we will: –Consider the problems of error handling without language support –Introduce error handling with dedicated language support and its advantages in Java 12

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Overview Errors and their classification Error handling without language support and its problems Basics of error handling with language support in Java Advantages of error handling with language support in Java Summary 13

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Error handling without language support Two possibilities for error signaling: –Program crash (!) – The extreme case are functions that do not signal errors at all but simply terminate the program: E.g., access to a non-existing file led to a program crash in older versions of Pascal –Errors are signaled in many languages by means of unusual return codes (e.g., –1 instead of a positive number) Catching and handling of errors: –Error handling is ignored by the programmer –Errors are handled by means of conditional logic 14

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Error handling without language support We consider the following case: –Errors are signaled by unusual return values –They are handled by conditional logic Problem: No separation of normal code from error handling Suppose we had a function that reads a whole file from hard disk into memory (in pseudo code): 15 readFile { open the file; determine its size; allocate that much memory; read the file into memory; close the file; }

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Error handling without language support The function seems simple at first sight… But it ignores all possible errors: –File cannot be opened –Length of file cannot be determined –Not enough space in memory to read the file –Reading from the file fails –File cannot be closed Including appropriate error handling may result in serious code bloat, as seen on the next slide 16

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Error handling without language support 17 errorCodeType readFile { initialize errorCode = 0; open the file; if (theFileIsOpen) { determine the length of the file; if (gotTheFileLength) { allocate that much memory; if (gotEnoughMemory) { read the file into memory; if (readFailed) { errorCode = -1; } } else { errorCode = -2; } } else { errorCode = -3; } close the file; if (theFileDidNotClose && errorCode == 0) { errorCode = -4; } else { errorCode = errorCode && -4; } } else { errorCode = -5; } return errorCode; }

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Error handling without language support Including error handling results in 29 instead of 7 lines of code - a factor of nearly 400%! The main purpose of the code gets lost in the code for the discovery, signaling and treating of errors. The logic flow of the code is hard to follow Makes finding programming errors harder –Is the file closed in case we are out of memory? It gets even worse if the function should be modified later! 18

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Error handling without language support Conclusion: trade-off between reliability and readability –If errors are handled, program structure gets complex (many “if” statements) –If errors are ignored, the reliability is lost 19 Exception handling without language support is not feasible!

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Overview Errors and their classification Error handling without language support and its problems Basics of error handling with language support in Java Advantages of error handling with language support in Java Summary 20

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Exception handling in Java Exceptions are Java objects The Java compiler enforces the treatment of certain types of errors If an error occurs in a method: –This method [or the runtime system] creates an exception object This object contains information about the type of the error, the state of the program at the time of the error, etc. –Exception raised ( throw keyword): control and the created exception object are yielded to the runtime system –The runtime system looks for code that can handle the raised (thrown) exception Candidates for providing handlers are methods in the call-chain of the method where the error occurred The call chain is searched backwards 21

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Throwing an exception 22 public class Car { public void start() { // … // battery might be (close to) empty // driver might not be authorized } The battery might be (close to) empty  Exception! BatteryLowException The driver may not be authorized for this car  Exception! SecurityException

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Throwing an exception 23 public class Car { //... public void start() { //... if (batteryLevel <= 5) throw new BatteryLowException( "Battery is empty"); if (!driver.isAuthorized()) throw new SecurityException( "No access rights"); // start the car } } Throw-Statement: " throw " Exception-Object. Constraint: Exception-Object must be of a subtype of type Exception (more in a minute). Almost always created in place by means of new Will not be accepted by the compiler!

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Declaration syntax: "throws" = {"," }. We can declare several exceptions to be thrown The Java compiler checks if the declaration is correct –Can exceptions occur which are not declared or will not be caught? Declaring potentially raised exceptions 24 public class Car { public void start() throws BatteryLowException, SecurityException { //... // start car } The method has to declare thrown exceptions in its signature. They belong to a method’s signature just like the return type.

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Calling methods that raise exceptions 25 //... car.start(); //... } public class Bar { //... public void doSomethingWithCar(Car car) { This code will not be accepted by the compiler! Reason: doSomethingWithCar calls a method that can eventually raise exceptions. These possible exceptions are ignored  Program crash!

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Handling raised exceptions 26 public class Bar { public void doSomethingWithCar (Car car) { //... try { car.start(); } catch (BatteryLowException bE) { // Exception handling } catch (SecurityException secEx) { // Exception handling } //... } } Operations that can throw exceptions are put in a try -block. This signals the willingness to catch and handle exceptions that occur in statements within the block. Catching and handling the exceptions happens in catch -blocks. 1. possibility: calling method handles exceptions eventually raised by called methods

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Handling raised exceptions Each catch block declares a formal parameter –Example: catch(SecurityException e) The parameter type determines the exception type that the catch -block catches and handles –Here: SecurityException The parameter (here: e ) is a local variable in the catch -block –Allows references to the exception object to handle within the catch block –Allows access to methods and attributes of the exception object referred to by e Exceptions are ordinary Java objects! Typical method calls: –e.getMessage() – accesses the error text –e.printStackTrace() – prints out the call stack when e was created 27

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Handling several exceptions of a block How to handle the case when several exceptions are thrown by the statements of a statement block? There can be several catch blocks for one try block! –Individual statements that potentially throw several exceptions are also put in a try block. The first appropriate catch block will be executed –Attention should be paid when exceptions are in an inheritance hierarchy (more in a minute)! 28

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Propagating errors in Java 29 public class Bar { public void doSomethingWithCar (Car car) throws BatteryLowException, SecurityException { //... car.start(); //... } 2. possibility: Calling method further throws exceptions potentially raised by called methods along the call chain 2. possibility: Calling method further throws exceptions potentially raised by called methods along the call chain

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Propagating errors in Java 30 :Client o2: Bar:Car o2.doSomethingWithCar() main start() Look up the first method with a catch -block for the raised exception and continue with that code. If none is found, the program ends with an error message. public class Client { public static void main(String[] args) { //... Car car =...; Bar o2 = new Bar(); o2.doSomethingWithCar(car); //... }

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Ensuring execution of certain actions How can one ensure that certain actions are always executed? Problem: In programs with exceptions, there are several possibilities to exit the program. –Sometimes the execution of certain actions must be guaranteed. –No matter whether an exception occurred or not Example: Writing to a successfully opened file –The file should always be closed, whether the data was written or not. 31

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Ensuring execution of certain actions 32 public void test() { Switch sw = new Switch(); try { sw.on(); // code that may throw exceptions sw.off(); } catch (BatteryLowException ebEx) { sw.off(); // don’t do this; it duplicates code System.err.println("Caught BatteryLowException"); } catch (SecurityException secEx) { sw.off(); // don’t do this; it duplicates code System.err.println("Caught SecurityException"); } Code duplication

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 The finally block Java provides a finally block The statements within the finally blocks are always executed –After finishing the try blocks if no exception has occurred –After finishing the catch blocks if an exception was thrown 33 public void test() { Switch sw = new Switch(); try { sw.on(); // code that may throw exceptions } catch (BatteryLowException ebEx) { //... } catch (SecurityException secEx) { //... } finally { sw.off(); } sw is turned off here independent of the concrete control flow of the program

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Advantages of the finally block The statements within the finally block are executed independent of exception occurrence –There is no duplicated code, which must be executed whether there is an exception or not. Attention: –Statements in the finally block can also throw exceptions! Closing files or network connections fails, NullPointerException,... –Handling the exceptions in finally blocks is done in the same way as in any other block... 34

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Overview Errors and their classification Error handling without language support and its problems Basics of error handling with language support in Java Advantages of error handling with language support in Java Summary 35

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Advantages of error handling with language support 1.Separation of the error handling from “normal” logic 2.Propagation of errors along the dynamic call chain 3.Distinction and grouping of different types of errors 4.Compiler ensures that certain types of errors get handled 36

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 1. Separation of error handling Java’s exception handling constructs enable separation of normal code and error handling Attention! Separation of exception handling does not save the work of discovering, signaling and recovering from errors –The separation is the advantage! 37 void readFile() { try { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } catch (FileOpenFailed) { doSomething; } catch (sizeDeterminationFailed) { doSomething; } catch (memoryAllocationFailed) { doSomething; } catch (readFailed) { doSomething; } catch (fileCloseFailed) { doSomething; }

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 2. Propagation of exceptions Suppose readFile is the fourth method in a call chain: method1, method2, method3, readFile Suppose method1 is the only method interested in handling errors occurring in readFile Without language support for exceptions, method2 and method3 must propagate the error codes of readFile until they reach method1. 38 method1 { call method2; } method2 { call method3; } method3 { call readFile; }

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Propagation of exceptions 39 method1 { errorCodeType error; error = call method2; if (error) doErrorProcessing; else proceed; } errorCodeType method2 { errorCodeType error; error = call method3; if (error) return error; else proceed; } errorCodeType method3 { errorCodeType error; error = call readFile; if (error) return error; else proceed; }

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Propagation of exceptions In contrast to this, the runtime system of Java automatically searches backwards through the call chain for methods that can handle the exceptions 40 method3 { try { call readFile; } catch (Exception e) { doErrorProcessing; } method2 throws Exception { call method3; } method1 throws Exception { call method2; }

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Java’s exception type hierarchy All exception types in Java inherit from the predefined class java.lang.Throwable 41 "hard" VM failures; should not be caught by a program can be ignored; need not be declared or handled can be extended by programmer

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 The class Throwable 42 Throwable() Throwable(String) getMessage(): String printStackTrace() printStackTrace(PrintStream)... Throwable creates a Throwable object with an error description returns the error description prints the call stack at the time during the execution when the Throwable object was created

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Methods of class Exception 43 public class ExceptionMethods { public static void main(String[] args) { try { throw new Exception("Here’s my Exception"); } catch (Exception e) { System.out.println("Caught exception"); System.out.println("e.getMessage(): "+e.getMessage()); System.out.println("e.toString(): "+e.toString()); System.out.println("e.printStackTrace():"); e.printStackTrace(); }

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 The Exception Hierarchy: Error Serious errors: Program cannot continue –E.g., class not found It does not make sense to handle errors –Handling them is not enforced by the compiler. –Will often lead to program crash 44

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Unchecked exceptions: RuntimeException Runtime exceptions are errors that can occur everywhere in the program, depending on run-time conditions: –Trying to call an operation on a variable with a null-reference, –Violation of array boundaries… These errors can be, but do not have to be handled 45

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Unchecked exceptions: RuntimeException Enforcing the programmer to handle run-time exceptions would render a program unreadable, as they can occur everywhere To handle NullPointerException, a catch block would be needed for every function call: Even if the programmer is sure that each variable in the program contains a valid object! The compiler cannot check this statically 46 public static void main(String[] args) { // possibly ArrayIndexOutOfBoundsException, // NumberFormatException Double doubleValue = Double.parseDouble(args[0]); //possibly ArrayIndexOutOfBoundsException, // NumberFormatException Integer intValue = Integer.parseInt(args[1]); }

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Checked exceptions 47 Several predefined classes FileNotFoundException IOException … Application specific exceptions: Defined by the programmer as (in)direct heirs of Exception. Checked exceptions are all exception types that inherit from Exception but not from RuntimeException

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Checked exceptions For certain exceptions the compiler enforces that they are handled  checked exceptions A method must either –catch checked exceptions occurring in its scope, or –Pass the exceptions along the call chain and declare them with a throws -clause 48 The scope of a method M is not only its own code, but also code of methods it calls. This definition is recursive.

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Grouping exceptions Exceptions are ordinary Java objects defined in ordinary Java classes and have their own inheritance hierarchy As such, one can define specialization / generalization relations between different exception types An IndexOutOfBoundsException is thrown if an index is out of scope –ArrayIndexOutOfBoundsException is a subclass that applies to array accesses –“Out of scope”: index is negative or greater than or equal to the array size The programmer of a method can choose to handle more or less specific exceptions. 49

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Grouping exceptions 50 public void op1() { //... catch (ArayIndexOutOfBoundsException invInd) { // do something with invInd } catch (NullPointerException npe) { // do something with npe } catch (NoSuchElementException eType) { // do something with eType } This version of op1 handles different array exceptions differently. public void op1() { //... catch (RuntimeException e) { // do something with e } Here all array exceptions are treated uniformly.

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Grouping exceptions 51 public void op1() { //... catch (RuntimeException e) { // do something with e } public void op1() { //... catch (Exception e) { // do something with e } One could also use conditional logic to distinguish between different subtypes of RuntimeException. But the first version is: Better documented Easier to maintain One can even treat ALL exceptions uniformly. NOT RECOMMENDED

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Grouping exceptions 52 public void op1() { try { //... } catch (RuntimeException e) { // do something with e } catch (ArayIndexOutOfBoundsException e) { // do something with invInd } public void op1() { try { //... } catch (ArrayIndexOutOfBoundsException invInd) { // do something with invInd } catch (RuntimeException e) { // do something with e } The runtime system chooses the first catch block that handles the type of an exception or one of its super-types. What happens if InvalidIndexException is thrown in each of the versions of op1?

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Is this code OK? public class CarException extends Exception {} public class NoGasoline extends CarException {} public class NoSpecialGasoline extends NoGasoline {} public class BadWeather extends Exception {} public class Car { public void start() throws NoGasoline { … } public void stop() throws CarException { … } } public class SportsCar extends Car { public void start() throws NoSpecialGasoline { … } public void stop() throws BadWeather { … } public static void main(String[] args) { try { new SportsCar().start(); } catch (NoSpecialGasoline e) { } } 53

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 “Inheritance” of Exceptions Rule 1: –If method x in the base class throws an exception, the overridden method x in a subclass may throw the same exception, or one derived from it. Rule 2: –The overridden subclass method cannot throw an exception that is not a type/subtype of an exception thrown by the method from its ancestor. 54

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Constructors and Exceptions We cannot have anything before the base-class constructor call using super(), not even a try block Exceptions of a base-class constructor must be declared in the signature of the derived-class constructor 55 public class Car { public Car() throws NoGasoline {} } public class SportsCar extends Car { public SportsCar throws NoGasoline { super(); //maybe throws a NoGasoline exception //... } NoGasoline may not be replaced by NoSpecialGasoline

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 What’s in a name? Name of the exception is typically the most important thing about it. Names tend to be long and descriptive. Code for the exception class itself is usually minimal. Once you catch the exception you typically are done with it. 56

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Rethrowing an Exception Perform anything you can locally, then let a global handler perform more appropriate activities. fillInStackTrace records within this Throwable object information about the current state of the stack frames for the current thread. 57 catch (Exception e) { System.out.println("An exception was thrown: "+e); throw e; // throw e.fillInStackTrace(); }

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Checking for expected exceptions in JUnit 4 Do you remember our calculator using JUnit in T12? –We had a test method „divideByZero()“ –We expect this test method to throw an ArithmeticException We want to be able to check for this expected exception –If it is thrown, the test has been passed (expected exception) –If it is not thrown, the test shall fail How can we “check” and catch the exception using JUnit? We use parameter for annotation In our = ArithmeticException.class) public void divideByZero() { calculator.divide(0); } 58

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Overview Errors and their classification Error handling without language support and its problems Basics of error handling with language support in Java Advantages of error handling with language support in Java Summary 59

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Summary Each program can potentially produce errors Java has explicit support for error handling –Errors: Heavyweight problems  cannot be handled –Exceptions are problems that can be handled There are basically three approaches to exceptions: –Declaration and propagation of exceptions via „ throws “ and exception type in the method head –Handing of exceptions in try…catch blocks of the method –Runtime exceptions can be ignored But they can also be handled! 60

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Summary Exception handling happens in try...catch –Statements that can create exceptions (mostly method calls) are put in a try block –Possible exceptions are handled in catch blocks –Each catch block handles one exception type –The concrete type is declared in the parameter of the catch block Searching for an appropriate catch happens top down –The first fitting catch block will be used –When ordering the catch blocks one should take into consideration the exception inheritance hierarchy! Statements in finally block will always be executed –No matter whether an exception was thrown or not –Ideal for cleaning up, e.g., closing open files 61

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Summary: Control Flow for Exceptions 1.Creation of an appropriate exception object The exception object describes the problem and potentially the cause Current class (name!), potentially the code line, problem description (text) The creation of the exception object can happen... „automatically“ by the runtime system (e.g., NullPointerException ) By method calls (e.g., FileNotFoundException ) By the programmer by means of „ throw new XXX() “ 2.The runtime system searches for a fitting catch starting with the current block up to the current method… continuing in the method that called the method at hand…...and so on in the call chain, eventually up to the start of the program 62

Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T16 Summary: flow of exception handling 63 Exception of type TE thrown in a try block exit try block execute instructions of the first such catch block yes Execute statements of the (optional) finally block catch block run without throwing new exceptions? execute statements of the (optional) finally block no continue after try block yes propagate the new Exception object to enclosing try block no (catch-type =TE or catch-type superclass of TE) found? Look-up catch blocks