SlideShare a Scribd company logo
1 of 23
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
Programmazione concorrente e distribuita
SUMMARY
 Exception handling
 Throwing an exception
 Catching exceptions
 Chaining
 Assertions
 Using assertions
 Logging
 Using loggers
 Handlers
 Appendix: Checked or Unchecked?
2Riccardo Cardin
Programmazione concorrente e distribuita
EXCEPTION HANDLING
 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
3Riccardo Cardin
Programmazione concorrente e distribuita
EXCEPTION HANDLING
 Throwing exceptions
 A method can signal a problem by throwing an
exception
 Decoupling of the process of detecting and handling errors
 Trying to fix in loco is not a good idea...
 ...let’s rise an exception, instead!
4Riccardo Cardin
private static Random generator = new Random();
public static int readInt(int low, int high) {
return low + (int) (generator.nextDouble() * (high – low + 1));
}
What if low > high ?
if (low > high)
throw new IllegalArgumentException(
String.format("%d is greater than %d!", low, high);
Programmazione concorrente e distribuita
EXCEPTION HANDLING
 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
5Riccardo Cardin
methodA(arg1, arg2)
methodB(arg1)
methodC(arg1, arg2, arg3)
methodD(arg1, arg2)
Exception
Programmazione concorrente e distribuita
EXCEPTION HANDLING
 The Exception hierarchy
6Riccardo Cardin
Programmazione concorrente e distribuita
EXCEPTION HANDLING
 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
7Riccardo Cardin
Programmazione concorrente e distribuita
EXCEPTION HANDLING
 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)
 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
8Riccardo Cardin
public void write(String str) throws IOException
/**
* @throws NullPointerException if filename is null
*/
public void write(String str) throws IOException
Programmazione concorrente e distribuita
EXCEPTION HANDLING
 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
 Supply every method you need to give information on the ex.
9Riccardo Cardin
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);
}
}
Programmazione concorrente e distribuita
EXCEPTION HANDLING
 Catching exceptions
 The handling of an exception is accomplished with a
try block
 Sharing one handler among multiple exception classes
10Riccardo Cardin
try {
// 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
}
The catch
clauses are
matched top
to bottom
and they
respect type
hierarchies
try {
// Statments that could throw an exception
} catch (ExceptionClass1 | ExceptionClass2 ex) {
// Handling of the exception of type ExceptionClass1 and 2
}
Java 7 and
above
Programmazione concorrente e distribuita
EXCEPTION HANDLING
 Resource management
 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»
11Riccardo Cardin
try (ResourceType1 res1 = init1; ResourceType2 res2 = init2) {
// Statments that use res1 and res2 and
// that could throw and exception
} catch (Exception ex) { /* ... */ }
Programmazione concorrente e distribuita
EXCEPTION HANDLING
 The finally clause
 It is executed when the try block comes to an end,
either normally or due to an exeption
 Avoid throwing exception in the finally block
 Shadowing of the original exception
 finally block should not contain a return
statement
12Riccardo Cardin
try {
// Statments
} catch (Exception ex) {
// Handle exception
} finally {
// Do some cleanup (release locks, close db connection, ...)
}
Programmazione concorrente e distribuita
EXCEPTION HANDLING
 Rethrowing and Chaining Exception
 It is possible in a catch block to rethrow and
exception
 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)
13Riccardo Cardin
try {
// Statments
} catch (Exception ex) {
// Do something
throw new Exception("Something is going on here", ex);
}
Programmazione concorrente e distribuita
EXCEPTION HANDLING
 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
 Put a marker in the stack trace, simplifying debugging ops
14Riccardo Cardin
public void process(String direction) {
this.direction = Objects.requireNonNull(direction);
}
Java 7 and
above
Programmazione concorrente e distribuita
ASSERTIONS
 A common idiom of defensive programming
 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
15Riccardo Cardin
assert condition;
assert condition : expression;
java –enableassertions MainClass // or -ea
java –disableassertions MainClass // or -da
Programmazione concorrente e distribuita
LOGGING
 The logging API overcomes the problems to deal
with System.out.println during debugging
 The logging system manages a default logger
 You can define your own logger
 First time you request a logger with a name, it is created
 Logger names are hierarchical
 Seven logging levels
16Riccardo Cardin
Logger.getGlobal().info("Opening file " + filename);
// Prints: Aug 04, 2014 09:53:34 AM com.company.MyClass read
// INFO: Opening file data.txt
Logger logger = Logger.getLogger("com.company.app");
OFF SEVERE WARNING INFO CONFIG FINE FINER FINEST ALL
Logger.setLevel(Level.FINE)
Programmazione concorrente e distribuita
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
 You can use a custom log handler
17Riccardo Cardin
# In jre/lib/logging.properties
java.util.logging.ConsoleHandler.level=INFO
Handler handler = new ConsoleHandler();
handler.setLevel(Level.FINE);
logger.setUseParentHandlers(false); // Inhibit parent handling
logger.addHandler(handler);
Programmazione concorrente e distribuita
LOGGING
 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
 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
18Riccardo Cardin
logger.setUseParentHandlers(false);
Programmazione concorrente e distribuita
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
 Joshua Bloch
19Riccardo Cardin
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.
Item 58: Use checked exceptions for recoverable conditions and runtime
exceptions for programming errors
Programmazione concorrente e distribuita
CHECKED OR UNCHECKED?
 "The use of checked is a path to the Dark Side"
 Robert C. Martin
 Violation of the Open / Close Principle
 Martin Fowler
 Proposes the Notification pattern
20Riccardo Cardin
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.
...on the whole I think that exceptions are good, but Java checked
exceptions are more trouble than they are worth.
Programmazione concorrente e distribuita
CHECKED OR UNCHECKED?
21Riccardo Cardin
Programmazione concorrente e distribuita
EXAMPLES
22Riccardo Cardin
https://github.com/rcardin/pcd-snippets
Programmazione concorrente e distribuita
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
23Riccardo Cardin

More Related Content

What's hot (20)

LinkedList vs Arraylist- an in depth look at java.util.LinkedList
LinkedList vs Arraylist- an in depth look at java.util.LinkedListLinkedList vs Arraylist- an in depth look at java.util.LinkedList
LinkedList vs Arraylist- an in depth look at java.util.LinkedList
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 
Inheritance in java
Inheritance in java Inheritance in java
Inheritance in java
 
Introduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita GanesanIntroduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita Ganesan
 
Java: Inheritance
Java: InheritanceJava: Inheritance
Java: Inheritance
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8
 
Java static keyword
Java static keywordJava static keyword
Java static keyword
 
java Applet Introduction
java Applet Introductionjava Applet Introduction
java Applet Introduction
 
Java IO
Java IOJava IO
Java IO
 
Nested class in java
Nested class in javaNested class in java
Nested class in java
 
Java String
Java String Java String
Java String
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Python programming : Threads
Python programming : ThreadsPython programming : Threads
Python programming : Threads
 
Class or Object
Class or ObjectClass or Object
Class or Object
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
 

Viewers also liked

Scala For Java Programmers
Scala For Java ProgrammersScala For Java Programmers
Scala For Java ProgrammersEnno Runne
 
Design Pattern Strutturali
Design Pattern StrutturaliDesign Pattern Strutturali
Design Pattern StrutturaliRiccardo Cardin
 
A (too) Short Introduction to Scala
A (too) Short Introduction to ScalaA (too) Short Introduction to Scala
A (too) Short Introduction to ScalaRiccardo Cardin
 
Design pattern architetturali Model View Controller, MVP e MVVM
Design pattern architetturali   Model View Controller, MVP e MVVMDesign pattern architetturali   Model View Controller, MVP e MVVM
Design pattern architetturali Model View Controller, MVP e MVVMRiccardo Cardin
 
Java - Concurrent programming - Thread's advanced concepts
Java - Concurrent programming - Thread's advanced conceptsJava - Concurrent programming - Thread's advanced concepts
Java - Concurrent programming - Thread's advanced conceptsRiccardo Cardin
 
Java - Processing input and output
Java - Processing input and outputJava - Processing input and output
Java - Processing input and outputRiccardo Cardin
 
Java- Concurrent programming - Synchronization (part 2)
Java- Concurrent programming - Synchronization (part 2)Java- Concurrent programming - Synchronization (part 2)
Java- Concurrent programming - Synchronization (part 2)Riccardo Cardin
 
Java- Concurrent programming - Synchronization (part 1)
Java- Concurrent programming - Synchronization (part 1)Java- Concurrent programming - Synchronization (part 1)
Java- Concurrent programming - Synchronization (part 1)Riccardo Cardin
 
Java Graphics Programming
Java Graphics ProgrammingJava Graphics Programming
Java Graphics ProgrammingRiccardo Cardin
 
Java - Remote method invocation
Java - Remote method invocationJava - Remote method invocation
Java - Remote method invocationRiccardo Cardin
 
SOLID - Principles of Object Oriented Design
SOLID - Principles of Object Oriented DesignSOLID - Principles of Object Oriented Design
SOLID - Principles of Object Oriented DesignRiccardo Cardin
 
Software architecture patterns
Software architecture patternsSoftware architecture patterns
Software architecture patternsRiccardo Cardin
 
Scala - the good, the bad and the very ugly
Scala - the good, the bad and the very uglyScala - the good, the bad and the very ugly
Scala - the good, the bad and the very uglyBozhidar Bozhanov
 
Java - Generic programming
Java - Generic programmingJava - Generic programming
Java - Generic programmingRiccardo Cardin
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections frameworkRiccardo Cardin
 
Design Pattern Architetturali - Dependency Injection
Design Pattern Architetturali - Dependency InjectionDesign Pattern Architetturali - Dependency Injection
Design Pattern Architetturali - Dependency InjectionRiccardo Cardin
 
Errori comuni nei documenti di Analisi dei Requisiti
Errori comuni nei documenti di Analisi dei RequisitiErrori comuni nei documenti di Analisi dei Requisiti
Errori comuni nei documenti di Analisi dei RequisitiRiccardo Cardin
 
Introduzione ai Design Pattern
Introduzione ai Design PatternIntroduzione ai Design Pattern
Introduzione ai Design PatternRiccardo Cardin
 

Viewers also liked (20)

Scala For Java Programmers
Scala For Java ProgrammersScala For Java Programmers
Scala For Java Programmers
 
Design Pattern Strutturali
Design Pattern StrutturaliDesign Pattern Strutturali
Design Pattern Strutturali
 
A (too) Short Introduction to Scala
A (too) Short Introduction to ScalaA (too) Short Introduction to Scala
A (too) Short Introduction to Scala
 
Design pattern architetturali Model View Controller, MVP e MVVM
Design pattern architetturali   Model View Controller, MVP e MVVMDesign pattern architetturali   Model View Controller, MVP e MVVM
Design pattern architetturali Model View Controller, MVP e MVVM
 
Java - Concurrent programming - Thread's advanced concepts
Java - Concurrent programming - Thread's advanced conceptsJava - Concurrent programming - Thread's advanced concepts
Java - Concurrent programming - Thread's advanced concepts
 
Java - Processing input and output
Java - Processing input and outputJava - Processing input and output
Java - Processing input and output
 
Java- Concurrent programming - Synchronization (part 2)
Java- Concurrent programming - Synchronization (part 2)Java- Concurrent programming - Synchronization (part 2)
Java- Concurrent programming - Synchronization (part 2)
 
Java- Concurrent programming - Synchronization (part 1)
Java- Concurrent programming - Synchronization (part 1)Java- Concurrent programming - Synchronization (part 1)
Java- Concurrent programming - Synchronization (part 1)
 
Java Graphics Programming
Java Graphics ProgrammingJava Graphics Programming
Java Graphics Programming
 
Java - Remote method invocation
Java - Remote method invocationJava - Remote method invocation
Java - Remote method invocation
 
SOLID - Principles of Object Oriented Design
SOLID - Principles of Object Oriented DesignSOLID - Principles of Object Oriented Design
SOLID - Principles of Object Oriented Design
 
Software architecture patterns
Software architecture patternsSoftware architecture patterns
Software architecture patterns
 
Diagrammi di Sequenza
Diagrammi di SequenzaDiagrammi di Sequenza
Diagrammi di Sequenza
 
Java - Sockets
Java - SocketsJava - Sockets
Java - Sockets
 
Scala - the good, the bad and the very ugly
Scala - the good, the bad and the very uglyScala - the good, the bad and the very ugly
Scala - the good, the bad and the very ugly
 
Java - Generic programming
Java - Generic programmingJava - Generic programming
Java - Generic programming
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
 
Design Pattern Architetturali - Dependency Injection
Design Pattern Architetturali - Dependency InjectionDesign Pattern Architetturali - Dependency Injection
Design Pattern Architetturali - Dependency Injection
 
Errori comuni nei documenti di Analisi dei Requisiti
Errori comuni nei documenti di Analisi dei RequisitiErrori comuni nei documenti di Analisi dei Requisiti
Errori comuni nei documenti di Analisi dei Requisiti
 
Introduzione ai Design Pattern
Introduzione ai Design PatternIntroduzione ai Design Pattern
Introduzione ai Design Pattern
 

Similar to Java Exception Handling, Assertions and Logging

Exception handling & logging in Java - Best Practices (Updated)
Exception handling & logging in Java - Best Practices (Updated)Exception handling & logging in Java - Best Practices (Updated)
Exception handling & logging in Java - Best Practices (Updated)Angelin R
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptionssaman Iftikhar
 
Exception handling and logging best practices
Exception handling and logging best practicesException handling and logging best practices
Exception handling and logging best practicesAngelin R
 
Itp 120 Chapt 18 2009 Exceptions & Assertions
Itp 120 Chapt 18 2009 Exceptions & AssertionsItp 120 Chapt 18 2009 Exceptions & Assertions
Itp 120 Chapt 18 2009 Exceptions & Assertionsphanleson
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-ivRubaNagarajan
 
Handling Exceptions In C & C++[Part A]
Handling Exceptions In C & C++[Part A]Handling Exceptions In C & C++[Part A]
Handling Exceptions In C & C++[Part A]ppd1961
 
Exception handling
Exception handlingException handling
Exception handlingzindadili
 
Java SE 11 Exception Handling
Java SE 11 Exception HandlingJava SE 11 Exception Handling
Java SE 11 Exception HandlingAshwin Shiv
 
JP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJAYAPRIYAR7
 
Exception Handling Mechanism in .NET CLR
Exception Handling Mechanism in .NET CLRException Handling Mechanism in .NET CLR
Exception Handling Mechanism in .NET CLRKiran Munir
 
Exception handling
Exception handlingException handling
Exception handlingRaja Sekhar
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handlingAlpesh Oza
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handlingAlpesh Oza
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handlingAlpesh Oza
 
Exception handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingException handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingPrabu U
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overviewBharath K
 

Similar to Java Exception Handling, Assertions and Logging (20)

Exception handling & logging in Java - Best Practices (Updated)
Exception handling & logging in Java - Best Practices (Updated)Exception handling & logging in Java - Best Practices (Updated)
Exception handling & logging in Java - Best Practices (Updated)
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
Exception handling and logging best practices
Exception handling and logging best practicesException handling and logging best practices
Exception handling and logging best practices
 
Itp 120 Chapt 18 2009 Exceptions & Assertions
Itp 120 Chapt 18 2009 Exceptions & AssertionsItp 120 Chapt 18 2009 Exceptions & Assertions
Itp 120 Chapt 18 2009 Exceptions & Assertions
 
Comp102 lec 10
Comp102   lec 10Comp102   lec 10
Comp102 lec 10
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
 
Handling Exceptions In C & C++[Part A]
Handling Exceptions In C & C++[Part A]Handling Exceptions In C & C++[Part A]
Handling Exceptions In C & C++[Part A]
 
Exception handling
Exception handlingException handling
Exception handling
 
Java SE 11 Exception Handling
Java SE 11 Exception HandlingJava SE 11 Exception Handling
Java SE 11 Exception Handling
 
JP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.ppt
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception Handling Mechanism in .NET CLR
Exception Handling Mechanism in .NET CLRException Handling Mechanism in .NET CLR
Exception Handling Mechanism in .NET CLR
 
Exception handling
Exception handlingException handling
Exception handling
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handling
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handling
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handling
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingException handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread Programming
 
Exceptions handling notes in JAVA
Exceptions handling notes in JAVAExceptions handling notes in JAVA
Exceptions handling notes in JAVA
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 

More from Riccardo Cardin

Java - Concurrent programming - Thread's basics
Java - Concurrent programming - Thread's basicsJava - Concurrent programming - Thread's basics
Java - Concurrent programming - Thread's basicsRiccardo Cardin
 
Design Pattern Comportamentali
Design Pattern ComportamentaliDesign Pattern Comportamentali
Design Pattern ComportamentaliRiccardo Cardin
 
Design Pattern Creazionali
Design Pattern CreazionaliDesign Pattern Creazionali
Design Pattern CreazionaliRiccardo Cardin
 
Mvc e di spring e angular js
Mvc e di   spring e angular jsMvc e di   spring e angular js
Mvc e di spring e angular jsRiccardo Cardin
 
Reactive programming principles
Reactive programming principlesReactive programming principles
Reactive programming principlesRiccardo Cardin
 

More from Riccardo Cardin (9)

Java - Concurrent programming - Thread's basics
Java - Concurrent programming - Thread's basicsJava - Concurrent programming - Thread's basics
Java - Concurrent programming - Thread's basics
 
Design Pattern Comportamentali
Design Pattern ComportamentaliDesign Pattern Comportamentali
Design Pattern Comportamentali
 
Design Pattern Creazionali
Design Pattern CreazionaliDesign Pattern Creazionali
Design Pattern Creazionali
 
Diagrammi di Attività
Diagrammi di AttivitàDiagrammi di Attività
Diagrammi di Attività
 
Diagrammi delle Classi
Diagrammi delle ClassiDiagrammi delle Classi
Diagrammi delle Classi
 
Diagrammi Use Case
Diagrammi Use CaseDiagrammi Use Case
Diagrammi Use Case
 
Introduzione a UML
Introduzione a UMLIntroduzione a UML
Introduzione a UML
 
Mvc e di spring e angular js
Mvc e di   spring e angular jsMvc e di   spring e angular js
Mvc e di spring e angular js
 
Reactive programming principles
Reactive programming principlesReactive programming principles
Reactive programming principles
 

Recently uploaded

What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 

Recently uploaded (20)

What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 

Java Exception Handling, Assertions and Logging

  • 1. 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
  • 2. Programmazione concorrente e distribuita SUMMARY  Exception handling  Throwing an exception  Catching exceptions  Chaining  Assertions  Using assertions  Logging  Using loggers  Handlers  Appendix: Checked or Unchecked? 2Riccardo Cardin
  • 3. Programmazione concorrente e distribuita EXCEPTION HANDLING  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 3Riccardo Cardin
  • 4. Programmazione concorrente e distribuita EXCEPTION HANDLING  Throwing exceptions  A method can signal a problem by throwing an exception  Decoupling of the process of detecting and handling errors  Trying to fix in loco is not a good idea...  ...let’s rise an exception, instead! 4Riccardo Cardin private static Random generator = new Random(); public static int readInt(int low, int high) { return low + (int) (generator.nextDouble() * (high – low + 1)); } What if low > high ? if (low > high) throw new IllegalArgumentException( String.format("%d is greater than %d!", low, high);
  • 5. Programmazione concorrente e distribuita EXCEPTION HANDLING  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 5Riccardo Cardin methodA(arg1, arg2) methodB(arg1) methodC(arg1, arg2, arg3) methodD(arg1, arg2) Exception
  • 6. Programmazione concorrente e distribuita EXCEPTION HANDLING  The Exception hierarchy 6Riccardo Cardin
  • 7. Programmazione concorrente e distribuita EXCEPTION HANDLING  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 7Riccardo Cardin
  • 8. Programmazione concorrente e distribuita EXCEPTION HANDLING  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)  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 8Riccardo Cardin public void write(String str) throws IOException /** * @throws NullPointerException if filename is null */ public void write(String str) throws IOException
  • 9. Programmazione concorrente e distribuita EXCEPTION HANDLING  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  Supply every method you need to give information on the ex. 9Riccardo Cardin 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); } }
  • 10. Programmazione concorrente e distribuita EXCEPTION HANDLING  Catching exceptions  The handling of an exception is accomplished with a try block  Sharing one handler among multiple exception classes 10Riccardo Cardin try { // 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 } The catch clauses are matched top to bottom and they respect type hierarchies try { // Statments that could throw an exception } catch (ExceptionClass1 | ExceptionClass2 ex) { // Handling of the exception of type ExceptionClass1 and 2 } Java 7 and above
  • 11. Programmazione concorrente e distribuita EXCEPTION HANDLING  Resource management  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» 11Riccardo Cardin try (ResourceType1 res1 = init1; ResourceType2 res2 = init2) { // Statments that use res1 and res2 and // that could throw and exception } catch (Exception ex) { /* ... */ }
  • 12. Programmazione concorrente e distribuita EXCEPTION HANDLING  The finally clause  It is executed when the try block comes to an end, either normally or due to an exeption  Avoid throwing exception in the finally block  Shadowing of the original exception  finally block should not contain a return statement 12Riccardo Cardin try { // Statments } catch (Exception ex) { // Handle exception } finally { // Do some cleanup (release locks, close db connection, ...) }
  • 13. Programmazione concorrente e distribuita EXCEPTION HANDLING  Rethrowing and Chaining Exception  It is possible in a catch block to rethrow and exception  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) 13Riccardo Cardin try { // Statments } catch (Exception ex) { // Do something throw new Exception("Something is going on here", ex); }
  • 14. Programmazione concorrente e distribuita EXCEPTION HANDLING  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  Put a marker in the stack trace, simplifying debugging ops 14Riccardo Cardin public void process(String direction) { this.direction = Objects.requireNonNull(direction); } Java 7 and above
  • 15. Programmazione concorrente e distribuita ASSERTIONS  A common idiom of defensive programming  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 15Riccardo Cardin assert condition; assert condition : expression; java –enableassertions MainClass // or -ea java –disableassertions MainClass // or -da
  • 16. Programmazione concorrente e distribuita LOGGING  The logging API overcomes the problems to deal with System.out.println during debugging  The logging system manages a default logger  You can define your own logger  First time you request a logger with a name, it is created  Logger names are hierarchical  Seven logging levels 16Riccardo Cardin Logger.getGlobal().info("Opening file " + filename); // Prints: Aug 04, 2014 09:53:34 AM com.company.MyClass read // INFO: Opening file data.txt Logger logger = Logger.getLogger("com.company.app"); OFF SEVERE WARNING INFO CONFIG FINE FINER FINEST ALL Logger.setLevel(Level.FINE)
  • 17. Programmazione concorrente e distribuita 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  You can use a custom log handler 17Riccardo Cardin # In jre/lib/logging.properties java.util.logging.ConsoleHandler.level=INFO Handler handler = new ConsoleHandler(); handler.setLevel(Level.FINE); logger.setUseParentHandlers(false); // Inhibit parent handling logger.addHandler(handler);
  • 18. Programmazione concorrente e distribuita LOGGING  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  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 18Riccardo Cardin logger.setUseParentHandlers(false);
  • 19. Programmazione concorrente e distribuita 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  Joshua Bloch 19Riccardo Cardin 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. Item 58: Use checked exceptions for recoverable conditions and runtime exceptions for programming errors
  • 20. Programmazione concorrente e distribuita CHECKED OR UNCHECKED?  "The use of checked is a path to the Dark Side"  Robert C. Martin  Violation of the Open / Close Principle  Martin Fowler  Proposes the Notification pattern 20Riccardo Cardin 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. ...on the whole I think that exceptions are good, but Java checked exceptions are more trouble than they are worth.
  • 21. Programmazione concorrente e distribuita CHECKED OR UNCHECKED? 21Riccardo Cardin
  • 22. Programmazione concorrente e distribuita EXAMPLES 22Riccardo Cardin https://github.com/rcardin/pcd-snippets
  • 23. Programmazione concorrente e distribuita 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 23Riccardo Cardin