Date post: | 09-Feb-2017 |
Category: |
Software |
Upload: | riccardo-cardin |
View: | 1,469 times |
Download: | 3 times |
EXCEPTION HANDLING, ASSERTIONS AND LOGGINGPROGRAMMAZIONE CONCORRENTE E DISTR.Università degli Studi di Padova
Dipartimento di Matematica
Corso di Laurea in Informatica, A.A. 2015 – [email protected]
2Programmazione concorrente e distribuita
SUMMARY Exception handling
Throwing an exceptionCatching exceptionsChaining
AssertionsUsing assertions
LoggingUsing loggersHandlers
Appendix: Checked or Unchecked?
Riccardo Cardin
3Programmazione concorrente e distribuita
EXCEPTION HANDLING Mechanism for transferring the control from the
point of failure to a component handlerDealing with the unexpected is more complex than
implementing the "happy path"!
Pitfalls using error codesThe caller is obliged to check for errorsProgrammers have to actively check and propagate
these error codesViolation of the Single Responsibility Principle
Riccardo Cardin
4Programmazione 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!
Riccardo 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);
5Programmazione concorrente e distribuita
EXCEPTION HANDLING Throwing exceptions
The normal flow of execution is interruptedNo value is returned to the callerThe control is transferred to a handler
The handler is searched in the call stack
Riccardo Cardin
methodA(arg1, arg2)
methodB(arg1)
methodC(arg1, arg2, arg3)
methodD(arg1, arg2)Exception
6Programmazione concorrente e distribuita
EXCEPTION HANDLING The Exception hierarchy
Riccardo Cardin
7Programmazione 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
Riccardo Cardin
8Programmazione 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
Riccardo Cardin
public void write(String str) throws IOException
/** * @throws NullPointerException if filename is null */public void write(String str) throws IOException
9Programmazione 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.
Riccardo 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); }}
10Programmazione 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
Riccardo 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
11Programmazione 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»
Riccardo Cardin
try (ResourceType1 res1 = init1; ResourceType2 res2 = init2) { // Statments that use res1 and res2 and // that could throw and exception} catch (Exception ex) { /* ... */ }
12Programmazione 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
Riccardo Cardin
try { // Statments} catch (Exception ex) { // Handle exception} finally { // Do some cleanup (release locks, close db connection, ...)}
13Programmazione 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)
Riccardo Cardin
try { // Statments} catch (Exception ex) { // Do something throw new Exception("Something is going on here", ex);}
14Programmazione 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
Riccardo Cardin
public void process(String direction) { this.direction = Objects.requireNonNull(direction);}
Java 7 and
above
15Programmazione 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
Riccardo Cardin
assert condition;assert condition : expression;
java –enableassertions MainClass // or -eajava –disableassertions MainClass // or -da
16Programmazione concorrente e distribuita
LOGGING The logging API overcomes the problems to deal
with System.out.println during debuggingThe 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
Riccardo 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)
17Programmazione concorrente e distribuita
LOGGING Log Handlers
Log handler are hierarchical, too Default handler (ancestor of all handler) has name " " and it
has type ConsoleHandlerFor a log, its logging level must be above the
threshold of both the logger and the handler
You can use a custom log handler
Riccardo Cardin
# In jre/lib/logging.propertiesjava.util.logging.ConsoleHandler.level=INFO
Handler handler = new ConsoleHandler();handler.setLevel(Level.FINE);logger.setUseParentHandlers(false); // Inhibit parent handlinglogger.addHandler(handler);
18Programmazione 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
Riccardo Cardin
logger.setUseParentHandlers(false);
19Programmazione 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 APICay Horstmann
Joshua Bloch
Riccardo 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
20Programmazione 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 PrincipleMartin Fowler
Proposes the Notification pattern Riccardo 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.
21Programmazione concorrente e distribuita
CHECKED OR UNCHECKED?
Riccardo Cardin
22Programmazione concorrente e distribuita
EXAMPLES
Riccardo Cardin
https://github.com/rcardin/pcd-snippets
23Programmazione 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.html
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
Riccardo Cardin