Exception Handling Advanced Programming Techniques https://no.wikipedia.org/wiki/tastatur#/media/file:computer_keyboard.png Prof. Dr. Bernhard Humm FB Informatik, Hochschule Darmstadt 1
Agenda Motivation Exceptions in Java Professional exception handling Literature Quick check 2
https://no.wikipedia.org/wiki/tastatur#/medi a/file:comput er_keyboard.png What are exceptions conceptually? Exceptions are undesired behaviour during the execution of a computer program 1. due to programming errors, e.g., division by zero 2. due to technical problems, e.g., network failures 3. due to faulty operation by the user, e.g., from date is greater than to date 4. due to exceptional business behaviour, e.g., credit limit is overdrawn Images: https://it.wikipedia.org/wiki/file:network-wired.svg https://openclipart.org/detail/180962/business-process-numbered 3
https://no.wikipedia.org/wiki/tastatur#/medi a/file:comput er_keyboard.png No computer program without exceptions Exceptions do occur: 1. Programming errors can be reduced by proper design an testing but cannot be avoided completely in complex systems 2. Technical problems can be reduced by redundancy etc. but cannot be avoided completely 3. Faulty operation can be reduced by ergonomic user interfaces but cannot be avoided completely 4. Exceptional business behaviour is part of the business and is not affected by computer programs Exceptions cannot be avoided. We have to handle them! 4 Images: https://it.wikipedia.org/wiki/file:network-wired.svg https://openclipart.org/detail/180962/business-process-numbered
Agenda Motivation Exceptions in Java Professional exception handling Literature Quick check 5
Exceptions as a programming construct in Java public class Exception1 extends Exception {... } void q(...) throws Exception1 {... throw new Exception1();... } Defining a checked exception Declaring a checked exception (unchecked exceptions need not be declared) Throwing an exception try { p(...); q(...); r(...); } catch (Exception1 e) { // exception handling } catch (Exception2 e) { // exception handling } finally { } // clean up Protected block Catching an exception Exception handling Clean-up 6
Types of Exceptions in Java Checked Exceptions Extend java.lang.exception Must be caught by client (catch) oder re-thrown (throws) Defined by JDK, e.g., FileNotFoundException Custom-code, e.g., MyException Compiler checks whether they are caught or not Unchecked Exceptions Extend java.lang.runtimeexception rsp. java.lang.error Used by JVM ArithmeticException NullPointerException ArrayIndexOutOfBoundsException Program crashes if not handled 7
Java Exception Hierarchy checked unchecked unchecked 8
Aren t Java Exceptions enough? Java Exceptions as a feature of the programming language do not automatically lead to a proper design of exception handling Sometimes Java Exceptions are even inappropriate! Business code tends to be littered with exception handling Exceptions may lead to spaghetti code: exceptions as the modern form of the go to statements (E. Dijkstra: Go to considered harmful ) 9
Exception handling may violate the principle of information hiding try { result = PaymentManager.transfer (100, account1, account2); } catch (DatabaseNotAvailableException e) { //?? } What can I do? I have knowledge on payment transactions only. I didn t even know that there was a database involved! class Dependency Client Serv er Client Serv er Client Interface Implementation The client knows the interface only, not the implementation The caught exception reveals implementation details. The implementation urges the client to handle the exception (checked exception) here, exception handling violates the principle of information hiding 10
Conventions for exception handling desperately needed! There is no commonly accepted convention for using exceptions, e.g.: - When to use checked exceptions, when unchecked exceptions? - When not to use exceptions at all? - Where to catch and handle exceptions? - How do handle exceptions? Textbooks on design and programming rarely cover professional exception handling (positive example: J. Siedersleben Moderne Softwarearchitektur) 11
Agenda Motivation Exceptions in Java Professional exception handling Literature Quick check 12
Professional exception handling: Classifying A/T exceptions Business Application exceptions A Exceptions Handle A exceptions Classify exceptions T Exceptions Handle T exceptions Technical exceptions 13
A Exceptions (Business Application exceptions) Exception that may occur in the business application context Must be specified in the interface Example: - Credit limit overdrawn in operation withdraw / transfer money of a banking application The service provider of an operation classifies the exceptions in A/T 14
Handling A Exceptions (Business application exceptions) Must be enumerated completely (this is always possible)! Are integral part of the interface Design alternatives for A exceptions: - Checked Exception - Return value Examples: void transfer (int amount, Account from, Account to) throws CreditLimitException /** @throws CreditLimitException if credit limit overdrawn */ int transfer (int amount, Account from, Account to) /** @return */ 0 if transfer successful -1 if credit limit overdrawn The client must handle the A exception (and is able to do so), e.g., inform the user, block the account, etc.! 15
T Exceptions (Technical exceptions) Exception that results from the implementation and its technology Examples: - Database not available in operation withdraw money of a banking application - Violated pre / post condition (resulting from programming errors) 16
Handling T Exceptions (Technical exceptions) Depend on the implementation and its technology In general, cannot be enumerated completely (Murphy s Law: If anything can go wrong it will ) Design Recommendations: - Not part of the interface! - Always use RuntimeExceptions for T Exceptions (JDK-defined or custom-defined) The client cannot handle T exceptions and, hence, should not attempt to do so! 17
What if some library throws checked T exceptions? If you are using libraries or neighbouring components that throw T exceptions as checked exceptions (in conflict with my recommendation): 1. Catch the exception (as enforced by the compiler) 2. Wrap it into a new RuntimeException (e.g., IllegalStateException, IllegalArgumentException, etc.) 3. Rethrow (exception chaining) Example: try { result = PaymentManager.transfer (100, account1, account2); } catch (DatabaseNotAvailableException e) { throw new RuntimeException(e); } 18
Who handles T exceptions? The ExceptionHandler Design recommendation: - Catch all T exceptions (RuntimeExceptions, Errors) at one central point within the system and pass them on to the ExceptionHandler - The ExceptionHandler classifies technical exceptions according to their severity and triggers corresponding actions try { // main system loop } catch (Throwable e) { exceptionhandler.handleexception(e) } class ExceptionHandler { void handleexception(throwable e) { // classify severity // perform corresponding action }... } In a 3-layer-architecture, the central point for catching T exceptions is usually at the client / server interface (application server) 19
T exception classification 1. Catastrophe (global severe problem) the entire system must be shut down 2. Local severe problem the user session must be terminated. In both cases, the user (if existing) must be informed. Clean-up work must be performed 3. Repairable problem the problem can be repaired, e.g., by retry or compensating actions 4. Uncritical problem The problem will be logged for maintenance purposes (applies for all 4 cases) and system operation can continue 20
Simple ExceptionHandler Implementation public class ExceptionHandler { } public static void activate () Thread.setDefaultUncaughtExceptionHandler( (Thread t, Throwable e) -> { Logger.getLogger(ExceptionHandler.class.getName()).severe("Fatal error: " + e); }); } 21
Agenda Motivation Exceptions in Java Professional exception handling Literature Quick check 22
Literature J. Siedersleben Johannes Siedersleben: Moderne Softwarearchitektur. dpunkt-verlag 2004 Chapter 5: Fehler und Ausnahmen Rechte und Pflichten 23
Agenda Motivation Exceptions in Java Professional exception handling Literature Quick check 24
Quick check: Exception handling 1. What are exceptions? 2. Why can they not be avoided in general? 3. What are the Java exception handling constructs? What are the differences between checked exceptions and unchecked exceptions? 4. How may exception handling violate the principle of information hiding? 5. How to classify exceptions in professional exception handling? 6. What are A exceptions? Who is responsible for handling them? 7. What are T exceptions? Who is responsible for handling them? 8. What is the exception handler? What is its responsibility? Where is it invoked? 25