ASSERTIONS AND LOGGING

Similar documents
SUMMARY INTRODUCTION CONCURRENT PROGRAMMING THREAD S BASICS. Introduction Thread basics. Thread states. Sequence diagrams

Programming II (CS300)

Programming II (CS300)

Chapter 13 Exception Handling

Programming in Java

Exceptions. CSC207 Winter 2017

17. Handling Runtime Problems

Designing Robust Classes

More on Exception Handling

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

Chapter 12 Exception Handling and Text IO. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 7

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

More on Exception Handling

A problem?... Exceptions. A problem?... A problem?... Suggested Reading: Bruce Eckel, Thinking in Java (Fourth Edition) Error Handling with Exceptions

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

Exception-Handling Overview

Assertions and Exceptions Lecture 11 Fall 2005

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

CS 3 Introduction to Software Engineering. 3: Exceptions

Exceptions - Example. Exceptions - Example

Correctness and Robustness

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

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

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

Exceptions and Libraries

COE318 Lecture Notes Week 10 (Nov 7, 2011)

Chapter 3 Java Exception

Chapter 14. Exception Handling and Event Handling ISBN

Sri Vidya College of Engineering & Technology Question Bank

16-Dec-10. Consider the following method:

Exceptions Handling Errors using Exceptions

BBM 102 Introduction to Programming II Spring Exceptions

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

6.Introducing Classes 9. Exceptions

Lecture 19 Programming Exceptions CSE11 Fall 2013

CSE 331 Software Design & Implementation

EXCEPTION-HANDLING INTRIVIEW QUESTIONS

Comp 249 Programming Methodology Chapter 9 Exception Handling

ECE 122. Engineering Problem Solving with Java

Defensive Programming. Ric Glassey

Motivations. Chapter 12 Exceptions and File Input/Output

Java Loose Ends. 11 December 2017 OSU CSE 1

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved.

Exceptions and assertions

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

Unit IV Generic Programming

Exceptions. Examples of code which shows the syntax and all that

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

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

BBM 102 Introduction to Programming II Spring 2017

Chapter 15. Exception Handling. Chapter Goals. Error Handling. Error Handling. Throwing Exceptions. Throwing Exceptions

2.6 Error, exception and event handling

Chapter 14. Exception Handling and Event Handling

Chapter 12 Exception Handling

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

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

EXCEPTION HANDLING. Summer 2018

Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws

Exception handling & logging Best Practices. Angelin

Program Correctness and Efficiency. Chapter 2

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

Exceptions and I/O: sections Introductory Programming. Errors in programs. Exceptions

Introductory Programming Exceptions and I/O: sections

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

Exceptions Chapter 10. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Assertions, pre/postconditions

SUMMARY INTRODUCTION COLLECTIONS FRAMEWORK. Introduction Collections and iterators Linked list Array list Hash set Tree set Maps Collections framework

Lecture 14 Summary 3/9/2009. By the end of this lecture, you will be able to differentiate between errors, exceptions, and runtime exceptions.

COSC 123 Computer Creativity. I/O Streams and Exceptions. Dr. Ramon Lawrence University of British Columbia Okanagan

Chapter 8. Exception Handling. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Exceptions and Error Handling


Data Structures. 02 Exception Handling

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

CSCI 261 Computer Science II

Software Construction

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

CS193j, Stanford Handout #25. Exceptions

Intro to Computer Science II. Exceptions

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

Checked and Unchecked Exceptions in Java

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

Introduction to Java. Handout-3a. cs402 - Spring

COMP1008 Exceptions. Runtime Error

CS Internet programming Unit- I Part - A 1 Define Java. 2. What is a Class? 3. What is an Object? 4. What is an Instance?

2IP15 Programming Methods

Programming with assertions Oracle guidelines

CSC207 Winter Section L5101 Paul Gries

Exceptions. Errors and Exceptions. Dealing with exceptions. What to do about errors and exceptions

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

SUMMARY FUTURES CALLABLES CONCURRENT PROGRAMMING THREAD S ADVANCED CONCEPTS

COP4020 Programming Languages. Exception Handling Prof. Robert van Engelen

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

Exceptions in Java

14. Exception Handling

Internal Classes and Exceptions

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

Java Exception. Wang Yang

The design of an ADT should evolve naturally during the problem-solving process Questions to ask when designing an ADT

Transcription:

SUMMARY Exception handling, ASSERTIONS AND LOGGING PROGRAMMAZIONE CONCORRENTE E DISTR. Università degli Studi di Padova Dipartimento di Matematica Corso di Laurea in Informatica, A.A. 2015 2016 rcardin@math.unipd.it Throwing an exception Catching exceptions Chaining Assertions Using assertions Logging Using loggers Handlers Appendix: Checked or Unchecked? 2 Mechanism for transferring the control from the point of failure to a component handler Dealing with the unexpected is more complex than implementing the "happy path"! Pitfalls using error codes The caller is obliged to check for errors Programmers have to actively check and propagate these error codes Violation of the Single Responsibility Principle Throwing exceptions A method can signal a problem by throwing an exception Decoupling of the process of detecting and handling errors private static Random generator = new Random(); public static int readint(int low, int high) { return low + (int) (generator.nextdouble() * (high low + 1)); Trying to fix in loco is not a good idea......let s rise an exception, instead! if (low > high) throw new IllegalArgumentException( String.format("%d is greater than %d!", low, high); What if low > high? 3 4

Throwing exceptions The normal flow of execution is interrupted No value is returned to the caller The control is transferred to a handler The handler is searched in the call stack The Exception hierarchy methoda(arg1, arg2) methodb(arg1) methodc(arg1, arg2, arg3) methodd(arg1, arg2) Exception 5 6 The Exception hierarchy Error Thrown when something exceptional happens that the program cannot be expected to handle OutOfMemoryError, StackOverflowError,... RuntimeException Unchecked exceptions indicate logic errors caused by programmers, not by unavoidable external risks NullPointerException, IllegalArgumentException,... Exception Checked exceptions (by the compiler), that must be either catched or declared in the method signature IOException Declaring checked exception Method that might give rise to a checked exception, must declare it in its header with a throws clause Superclass combination (not a good idea) public void write(string str) throws IOException An overriding method can throw at most the same checked exceptions of the overriden method Use javadoc @throws tag to document when a method throws and exception /** * @throws NullPointerException if filename is null */ public void write(string str) throws IOException 7 8

It s possible to create your own exception Extend Exception, RuntimeException or another existing exception class Supply different ctors, such as a default ctor, a ctor with a string message and a ctor with a Throwable public class MyException extends Exception { public MyException() { public MyException(String message) { // The error message shown in stack trace super(message); public MyException(Throwable cause) { // Cause is the exception that generate this exception super(cause); Supply every method you need to give information on the ex. Catching exceptions The handling of an exception is accomplished with a try block // Statments that could throw an exception catch (ExceptionClass1 ex) { // Handling of the exception of type ExceptionClass1 catch (ExceptionClass2 ex) { // Handling of the exception of type ExceptionClass2 Sharing one handler among multiple exception classes The catch clauses are matched top to bottom and they respect type hierarchies Java 7 and // Statments that could throw an exception above catch (ExceptionClass1 ExceptionClass2 ex) { // Handling of the exception of type ExceptionClass1 and 2 9 10 Resource management try (ResourceType1 res1 = init1; ResourceType2 res2 = init2) { // Statments that use res1 and res2 and // that could throw and exception catch (Exception ex) { /*... */ When try block exits, exception or not, the close methods of all resources objects are invoked Resources must implement AutoClosable interface Resources are closed in reverse order of their initialization If a close method throws an exception, it is normally propagated If both a statement in the try block and a close method throw an exception, the former is propagated The latter is attached as «suppressed» The finally clause It is executed when the try block comes to an end, either normally or due to an exeption // Statments catch (Exception ex) { // Handle exception finally { // Do some cleanup (release locks, close db connection,...) Avoid throwing exception in the finally block Shadowing of the original exception finally block should not contain a return statement 11 12

Rethrowing and Chaining Exception It is possible in a catch block to rethrow and exception // Statments catch (Exception ex) { // Do something throw new Exception("Something is going on here", ex); Don t know how to manage it, but want to log the failure The compiler tracks the correct flow of exception types Change the class of the thrown exception Use the proper constructor or the initcause method (old school) The Stack trace If an exception is not caught anywhere, a stack trace is displayed. By default it is sent to System.err Thread.setDefaultUncaughtExceptionHandler changes the default exception handling policy ex.printstacktrace() prints on System.out the stack trace of an exception It s possible to pass a stream to the above method Checking nullability public void process(string direction) { this.direction = Objects.requireNonNull(direction); Put a marker in the stack trace, simplifying debugging ops Java 7 and above 13 14 ASSERTIONS LOGGING A common idiom of defensive programming assert condition; assert condition : expression; Assertions allow to put in checks during test and to have them automatically removed in production code Throws and AssertionError if it is false Expression value is passed into the error Intended as a debugging aid for validating internal assumptions Enable / disable assertion at runtime java enableassertions MainClass // or -ea java disableassertions MainClass // or -da The logging API overcomes the problems to deal with System.out.println during debugging The logging system manages a default logger Logger.getGlobal().info("Opening file " + filename); // Prints: Aug 04, 2014 09:53:34 AM com.company.myclass read // INFO: Opening file data.txt You can define your own logger First time you request a logger with a name, it is created Logger names are hierarchical Logger logger = Logger.getLogger("com.company.app"); Seven logging levels Logger.setLevel(Level.FINE) OFF SEVERE WARNING INFO CONFIG FINE FINER FINEST ALL 15 16

LOGGING LOGGING Log Handlers Log handler are hierarchical, too Default handler (ancestor of all handler) has name " " and it has type ConsoleHandler For a log, its logging level must be above the threshold of both the logger and the handler # In jre/lib/logging.properties java.util.logging.consolehandler.level=info You can use a custom log handler Handler handler = new ConsoleHandler(); handler.setlevel(level.fine); logger.setuseparenthandlers(false); // Inhibit parent handling logger.addhandler(handler); Log Handlers By default, a logger sends records both to its own handlers and the handlers of the parent. To prevent double logging, use setuseparenthandlers logger.setuseparenthandlers(false); There exist two other handlers in the logging API SocketHandler Sends records to a specified host and port FileHandler Collects records in a file (javan.log in user s home dir.) Written in XML Highly configurable using the logging configuration file 17 18 CHECKED OR UNCHECKED? CHECKED OR UNCHECKED? Checked or un unchecked, which is better? There is a active and never ending debate on this question in Java, but no «right absolute answer». "Use the checked ones, Luke!" A checked exception is part of a method API Cay Horstmann Unchecked exceptions indicate logic errors caused by programmers, not by unavoidable external risks [..] Checked exceptions are used in a situation where failure should be anticipated. Joshua Bloch Item 58: Use checked exceptions for recoverable conditions and runtime exceptions for programming errors "The use of checked is a path to the Dark Side" Robert C. Martin If you throw a checked exception from a method in your code and the catch is three levels above, you must declare that exception in the signature of each method between you and the catch. This means that a change at a low level of the software can force signature changes on many higher levels. The changed modules must be rebuilt and redeployed, even though nothing they care about changed. Violation of the Open / Close Principle Martin Fowler...on the whole I think that exceptions are good, but Java checked exceptions are more trouble than they are worth. Proposes the Notification pattern 19 20

CHECKED OR UNCHECKED? EXAMPLES https://github.com/rcardin/pcd snippets 21 22 REFERENCES Chap. 5 «Exceptions, Assertions, and Logging», Core Java for the Impatient, Cay Horstmann, 2015, Addison Wesley Replacing Throwing Exceptions with Notification in Validations http://martinfowler.com/articles/replacethrowwithnotification.ht ml Chap. 7 «Error handling», Clean Code A Handbook of Agile Software Craftmanship, Robert C. Martin, 2008, Prentice Hall «Item 58: Use checked exceptions for recoverable conditions and runtime exceptions for programming errors», Effective Java, Joshua Bloch, 2008, Addison Wesley 23