26
Effective use of exception handling in Java Ankit

Exception Handling Java

Embed Size (px)

DESCRIPTION

An easy way to understand the exceptions & error in java

Citation preview

Page 1: Exception Handling Java

Effective use of exception handling in Java

Ankit

Page 2: Exception Handling Java

Overview

What is an exception ? Nature of exceptions Conditions where exception could be

generated Types of exceptions in Java Checked Vs Unchecked exceptions Contingency & Fault

Page 3: Exception Handling Java

What is exception ?

An abnormal condition, therefore, would be any condition that wouldn't reasonably be expected as part of the "normal functioning" of a method.

Exceptional conditions are not necessarily rare.

Page 4: Exception Handling Java

The Nature of exception

Exceptions due to programming errorsExceptions are generated due to programming errors (e.g., NullPointerException and IllegalArgumentException). The client code usually cannot do anything about programming errors.

Exceptions due to client code errorsClient code attempts something not allowed by the API, and thereby violates its contract.

Exceptions due to resource failuresExceptions that get generated when resources fail. For example: network connection fails.

Page 5: Exception Handling Java

Conditions where Exception could be generated. The parameters given to the method are not well defined

(i.e. are wrong / null where they must not be) The "constellation" of the parameter values are not

expected in the given way by the method (because if parameter "a" has a certain value, "b" must not be of another certain value)

The caller of the method simply calls it in an improper way (i.e. the environmental conditions are not correct, needed resources are not allocated yet etc.)

Page 6: Exception Handling Java

Cont…

The method allocates external resources (i.e. open connections, file handles etc.) and does not free them (thus leading to an invalid internal state of the program, the operating system or other components like databases)

The method relies on external resources (i.e. file system, database etc.) which are not available at the moment they are needed

Page 7: Exception Handling Java

Types of Exceptions in Java

Checked exceptions: Exceptions that inherit from the Exception class are checked exceptions. Client code has to handle the checked exceptions thrown by the API, either in a catch clause or by forwarding it outward with the throws clause.

Unchecked exceptions: RuntimeException also extends from Exception. However, all of the exceptions that inherit from RuntimeException get special treatment. There is no requirement for the client code to deal with them, and hence they are called unchecked exceptions.

Page 8: Exception Handling Java
Page 9: Exception Handling Java
Page 10: Exception Handling Java

What is java.lang.Error ?

Errors (members of the Error family) are usually thrown for more serious problems, such as OutOfMemoryError, that may not be so easy to handle. In general, code you write should throw only exceptions, not errors. Errors are usually thrown by the methods of the Java API, or by the Java virtual machine itself.

Page 11: Exception Handling Java
Page 12: Exception Handling Java

Why against throwing “Error” ?

Errors usually signal abnormal conditions that you wouldn't want a program to handle. Problems with linking, such as NoClassDefFoundError, or memory, such as StackOverflowError, could happen just about anywhere in a program. In the rare cases in which they happen, it is usually reasonable that the thread terminate.

Java Language Specification advises against throwing errors. It is intended that errors be thrown only by the Java runtime.

Page 13: Exception Handling Java

Checked vs. Unchecked exceptions

Ask yourself

"What action can the client code take when the exception occurs?"

Page 14: Exception Handling Java

Client's reaction when exception happens

Exception type

Client code cannot do anything

Make it an unchecked exception

Client code will take some useful recovery action based on information in exception

Make it a checked exception

Page 15: Exception Handling Java

Cont…

If you are throwing an exception to indicate an improper use of your class, you are signalling a software bug. The class of exception you throw probably should descend from RuntimeException, which will make it unchecked.

If you are throwing an exception to indicate not a software bug but an abnormal condition that client programmers should deal with every time they use your method, your exception should be checked.

Page 16: Exception Handling Java

throws Vs try-catch

If you feel that a method doesn't know how to handle a particular error, you can throw an exception from the method and let someone else deal with it. If you throw a "checked" exception, you enlist the help of the Java compiler to force client programmers to deal with the potential exception, either by catching it or declaring it in the throws clause of their methods.

Page 17: Exception Handling Java

Another Approach to decide whether to use checked exception or unchecked.

One design approach often discussed in the context of object-oriented programming is the Design by Contract approach. This approach to software design says that a method represents a contract between the client (the caller of the method) and the class that declares the method. The contract includes preconditions that the client must fulfil and postconditions that the method itself must fulfil.

Page 18: Exception Handling Java

What information does java.lang.Exception contain

The type of exception -- the exception class

Where the exception occurred -- the stack trace

Context and explanatory information -- the error message, and other state information

Page 19: Exception Handling Java

An approach to design your application

Page 20: Exception Handling Java

Contingency & Fault

ContingencyAn expected condition demanding an alternative response from a method that can be expressed in terms of the method's intended purpose. The caller of the method expects these kinds of conditions and has a strategy for coping with them.

FaultAn unplanned condition that prevents a method from achieving its intended purpose that cannot be described without reference to the method's internal implementation.

Page 21: Exception Handling Java

Mapping to java exceptionCondition Contingency Fault

Is considered to be A part of the design A nasty surprise

Is expected to happen rarely Never

Who cares about it The upstream code that invokes the method

The people who need to fix the problem

Examples Alternative return modes

Programming bugs, hardware malfunctions, configuration mistakes, missing files, unavailable servers

Best Mapping A checked exception An unchecked exception

Page 22: Exception Handling Java

Goals of a successful fault handling

framework

Minimize code clutter

Alert the right person

Exit the activity gracefully

Page 23: Exception Handling Java

Establish a “Fault Barrier”

The fault barrier resides logically toward the top of the call stack where it stops the upward propagation of an exception before default action is triggered.

The first responsibility of a fault barrier component is to record the information contained in the fault exception for future action.

The next responsibility of a fault barrier is to close out the operation in a controlled manner

Page 24: Exception Handling Java
Page 25: Exception Handling Java

References

http://www.onjava.com/pub/a/onjava/2003/11/19/exceptions.html http://dev2dev.bea.com/pub/a/2006/11/effective-exceptions.html?

page=2 http://www.cs.utexas.edu/~lavender/courses/tutorial/java-09.pdf http://en.wikipedia.org/wiki/Design_by_contract http://www.artima.com/designtechniques/desexcept2.html http://www.artima.com/designtechniques/exceptions.html http://goit-postal.blogspot.com/2007/05/thoughts-on-successful-

exception.html http://www.artima.com/designtechniques/exceptions7.html http://www.artima.com/designtechniques/desexcept3.html http://java.sun.com/docs/books/tutorial/essential/exceptions/

runtime.html

Page 26: Exception Handling Java

Thank you