Exception Handling Advanced Programming Techniques

Similar documents
CS 3 Introduction to Software Engineering. 3: Exceptions

C16b: Exception Handling

Data Structures. 02 Exception Handling

EXCEPTION HANDLING. Summer 2018

Documenting Advanced Programming Techniques

BBM 102 Introduction to Programming II Spring Exceptions

Chapter 13 Exception Handling

Exceptions - Example. Exceptions - Example

CS115. Chapter 17 Exception Handling. Prof. Joe X. Zhou Department of Computer Science. To know what is exception and what is exception handling

Exceptions. What exceptional things might our programs run in to?

BBM 102 Introduction to Programming II Spring 2017

CS159. Nathan Sprague

17. Handling Runtime Problems

CS159. Nathan Sprague

Pages and 68 in [JN] conventions for using exceptions in Java. Chapter 8 in [EJ] guidelines for more effective use of exceptions.

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Internal Classes and Exceptions

Introduction Advanced Programming Techniques

ITI Introduction to Computing II

Exceptions. CSC207 Winter 2017

ITI Introduction to Computing II

Java Errors and Exceptions. Because Murphy s Law never fails

About This Lecture. Outline. Handling Unusual Situations. Reacting to errors. Exceptions

Exception Handling. Exception Handling

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

Programming II (CS300)

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

ECE 122. Engineering Problem Solving with Java

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:

Exceptions. Produced by. Algorithms. Eamonn de Leastar Department of Computing, Maths & Physics Waterford Institute of Technology

Day 8. COMP1006/1406 Summer M. Jason Hinek Carleton University

Exception in thread "main" java.lang.arithmeticexception: / by zero at DefaultExceptionHandling.main(DefaultExceptionHandling.

13: Error Handling with Exceptions. The basic philosophy of Java is that "badly formed code will not be run."

What are Exceptions?

National University. Faculty of Computer Since and Technology Object Oriented Programming

Exceptions. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar

Introduction. Exceptions: An OO Way for Handling Errors. Common Runtime Errors. Error Handling. Without Error Handling Example 1

Exception-Handling Overview

Programming II (CS300)

Correctness and Robustness

COMP-202 Unit 9: Exceptions

COMP-202 Unit 9: Exceptions

Comp 249 Programming Methodology Chapter 9 Exception Handling

EXCEPTION-HANDLING INTRIVIEW QUESTIONS

For more details on SUN Certifications, visit

Full file at Chapter 2 - Inheritance and Exception Handling

Inheritance. SOTE notebook. November 06, n Unidirectional association. Inheritance ("extends") Use relationship

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages

COE318 Lecture Notes Week 10 (Nov 7, 2011)

PIC 20A Exceptions. Ernest Ryu UCLA Mathematics. Last edited: November 27, 2017

Exceptions in Java

Chapter 11 Handling Exceptions and Events. Chapter Objectives

16-Dec-10. Consider the following method:

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

Exceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1.

Chapter 12 Exception Handling

Interfaces Advanced Programming Techniques

Errors and Exceptions

Sri Vidya College of Engineering & Technology Question Bank

Exception Handling in Java

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1

Introduction Unit 4: Input, output and exceptions

Lecture 19 Programming Exceptions CSE11 Fall 2013

CSE 143 Java. Exceptions 1/25/

Introduction to Computation and Problem Solving. Class 25: Error Handling in Java. Prof. Steven R. Lerman and Dr. V. Judson Harward.

More on Exception Handling

More on Exception Handling

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

Reminder. Topics CSE What Are Exceptions?! Lecture 11 Exception Handling

Fundamentals of Object Oriented Programming

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

Interfaces Advanced Programming Techniques

Object-Oriented Programming in the Java language

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

COMP200 EXCEPTIONS. OOP using Java, based on slides by Shayan Javed

CS112 Lecture: Exceptions and Assertions

CS 61B Data Structures and Programming Methodology. July 7, 2008 David Sun

CS112 Lecture: Exceptions. Objectives: 1. Introduce the concepts of program robustness and reliability 2. Introduce exceptions

Binary search. int index = Collections.binarySearch(list, element);

Exceptions, try - catch - finally, throws keyword. JAVA Standard Edition

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11

CS1020 Data Structures and Algorithms I Lecture Note #8. Exceptions Handling exceptional events

ASSERTIONS AND LOGGING

Exception Handling in Java. An Exception is a compile time / runtime error that breaks off the

JAC444 - Lecture 4. Segment 1 - Exception. Jordan Anastasiade Java Programming Language Course

Assertions and Exceptions Lecture 11 Fall 2005

Chapter 14. Exception Handling and Event Handling ISBN

14. Exception Handling

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

Exceptions and assertions

Exception Handling. General idea Checked vs. unchecked exceptions Semantics of... Example from text: DataAnalyzer.

To Think About. MyClass.mogrify(new int[] { 1, 2, 4, 6 }));

What is the purpose of exceptions and exception handling? Vocabulary: throw/raise and catch/handle Exception propagation Java checked and unchecked

Chapter 11 Exception Handling

CS 200 Command-Line Arguments & Exceptions Jim Williams, PhD

Java Exception. Wang Yang

COMP-202. Exceptions. COMP Exceptions, 2011 Jörg Kienzle and others

Exceptions Handling Errors using Exceptions

2.6 Error, exception and event handling

CMSC131. Exceptions and Exception Handling. When things go "wrong" in a program, what should happen.

Transcription:

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