Ce diaporama a bien été signalé.
Nous utilisons votre profil LinkedIn et vos données d’activité pour vous proposer des publicités personnalisées et pertinentes. Vous pouvez changer vos préférences de publicités à tout moment.
Exception handling in java
What is Exception
 An exception is an event, which occurs
during the execution of a program, that
disrupts the normal flo...
Try catch finally
try {
//do something
} catch (ExceptionType name) {
} catch (ExceptionType name) {
} finally {
//clean u...
Advantages
 Separating Error-Handling Code from
"Regular" Code
 Propagating Errors Up the Call Stack
 Grouping and Diff...
Exception Type Hierarchy
Checked exceptions
 Part of the method signature
 Compile type checking
 Requires programmer to handle the
exception or...
Unchecked exceptions
 No need to declare the exception in
method’s signature
 No compile time checking
 Usually indicat...
Error
 Indicate error in the underlying JVM
 Error are external to the application
 Application does not usually have t...
When to throw exceptions
 Exceptions indicate a broken contract
 Precondition (e.g. file is open for read)
 Postconditi...
What to throw?
 Exceptions v/s Errors
 Errors are for JVM
 Exceptions for rest of us

 Checked v/s Unchecked exception...
When to catch exception
1. When you can handle the exception
2. When you need to throw a different
type of exception
3. Re...
When not to throw an
exception


To achieve Flow control using exception

try {

}

while (true) {
increaseCount();
}
} c...
3 rules
 What went wrong?
 Where did it go wrong?
 Why did it go wrong?
 If your exception does not provide
answers to...
Performance implications of
exceptions
 Exceptions are expensive for the JVM
 Creating stack traces requires
resources a...
Anti Patterns










Log and Throw
Throwing Generic Exception
Catching Generic Exception
Destructive Wrapping
...
Anti Patterns - Log and Throw
 Log the error and throw the same
exception again
 Messy log file
 Achieves nothing
Anti Patterns - Throwing Generic
Exception
 The caller does not know the nature
of error – hinders error handling
Anti Patterns - Catching Generic
Exception
 We are masking programming errors
public SomeInterface buildInstance(String
className) {
SomeInterface impl = null;
try {
Class clazz = Class.forName(classN...
Anti Patterns - Destructive
Wrapping
catch (NoSuchMethodException e) {
throw new MyServiceException("Blah:
"+
e.getMessage...
Anti Patterns - Log and Return Null
catch (NoSuchMethodException e) {
LOG.error("Blah", e);
return null;
}
Anti Patterns - Catch and Ignore
(a.k.a. Head in the Sand)
catch (NoSuchMethodException e) {
}
Anti Patterns - Throw from Within
Finally
try {
blah();
} finally {
cleanUp();
}
Anti Patterns - Multi-Line Log
Messages
LOG.debug("Using cache policy A");
LOG.debug("Using retry policy B");
Anti Patterns - Unsupported
Operation Returning Null
public String foo() {
// Not supported in this
implementation.
return...
Best practices
 Throw checked exception when caller can recover
from error
 Throw runtime exception when the caller cann...
Exception chaining
try{
..some code that throws
XXXException
}catch(XXXException ex){
throw new RuntimeException(ex);
}
Exception logging
 Log all internal states
 Log all parameters to the method
that failed
 Log all data required to trac...
Exceptions in a typical enterprise
applications
 Define a hierarchy of exceptions.
 Lower level module throws lower leve...
Exceptions and Transactions
 @ApplicationException(rollback=true)
public class FooException extends
Exception ...
Questions
references
Best practices in EJB exception handling
http://www.ibm.com/developerworks/library/j-ejbexcept.html
Beware the ...
References (cont…)
JAVA EXCEPTIONS
http://www.javaolympus.com/J2SE/Exceptions/JavaExceptions.jsp
Exception-Handling Antipa...
Prochain SlideShare
Chargement dans…5
×

Exception handling in java

Best practices on how to work with exceptions in Java

  • Soyez le premier à commenter

Exception handling in java

  1. 1. Exception handling in java
  2. 2. What is Exception  An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.
  3. 3. Try catch finally try { //do something } catch (ExceptionType name) { } catch (ExceptionType name) { } finally { //clean up }
  4. 4. Advantages  Separating Error-Handling Code from "Regular" Code  Propagating Errors Up the Call Stack  Grouping and Differentiating Error Types
  5. 5. Exception Type Hierarchy
  6. 6. Checked exceptions  Part of the method signature  Compile type checking  Requires programmer to handle the exception or declare the method as throws exception  Unique to java  e.g. FileNotFoundException
  7. 7. Unchecked exceptions  No need to declare the exception in method’s signature  No compile time checking  Usually indicate programming error  e.g. NullPointerException
  8. 8. Error  Indicate error in the underlying JVM  Error are external to the application  Application does not usually have to deal with these class of Exceptions  e.g. OutOfMemoryError
  9. 9. When to throw exceptions  Exceptions indicate a broken contract  Precondition (e.g. file is open for read)  Postcondition (e.g. read a character from file)  Your method encounters an abnormal condition that it can't handle  If your method is unable to fulfill its contract, throw either a checked or unchecked exception.
  10. 10. What to throw?  Exceptions v/s Errors  Errors are for JVM  Exceptions for rest of us  Checked v/s Unchecked exceptions  Can caller recover from this error?  Yes: checked  No: unchecked
  11. 11. When to catch exception 1. When you can handle the exception 2. When you need to throw a different type of exception 3. Refer to 1 & 2
  12. 12. When not to throw an exception  To achieve Flow control using exception try { } while (true) { increaseCount(); } } catch (MaximumCountReachedException ex) { } //Continue execution public void increaseCount() throws MaximumCountReachedException { if (count >= 5000) throw new MaximumCountReachedException(); }
  13. 13. 3 rules  What went wrong?  Where did it go wrong?  Why did it go wrong?  If your exception does not provide answers to all these questions, you are doing something wrong!
  14. 14. Performance implications of exceptions  Exceptions are expensive for the JVM  Creating stack traces requires resources and CPU  the Java VM requires more efforts to handle a thrown exception than a normal method
  15. 15. Anti Patterns          Log and Throw Throwing Generic Exception Catching Generic Exception Destructive Wrapping Log and Return Null Catch and Ignore (a.k.a. Head in the Sand) Throw from Within Finally Multi-Line Log Messages Unsupported Operation Returning Null
  16. 16. Anti Patterns - Log and Throw  Log the error and throw the same exception again  Messy log file  Achieves nothing
  17. 17. Anti Patterns - Throwing Generic Exception  The caller does not know the nature of error – hinders error handling
  18. 18. Anti Patterns - Catching Generic Exception  We are masking programming errors
  19. 19. public SomeInterface buildInstance(String className) { SomeInterface impl = null; try { Class clazz = Class.forName(className); impl = (SomeInterface)clazz.newInstance(); } catch (Exception e) { log.error("Error creating class: " + className); } return impl; }
  20. 20. Anti Patterns - Destructive Wrapping catch (NoSuchMethodException e) { throw new MyServiceException("Blah: "+ e.getMessage()); }
  21. 21. Anti Patterns - Log and Return Null catch (NoSuchMethodException e) { LOG.error("Blah", e); return null; }
  22. 22. Anti Patterns - Catch and Ignore (a.k.a. Head in the Sand) catch (NoSuchMethodException e) { }
  23. 23. Anti Patterns - Throw from Within Finally try { blah(); } finally { cleanUp(); }
  24. 24. Anti Patterns - Multi-Line Log Messages LOG.debug("Using cache policy A"); LOG.debug("Using retry policy B");
  25. 25. Anti Patterns - Unsupported Operation Returning Null public String foo() { // Not supported in this implementation. return null; }  Throw UnsupportedOperationException
  26. 26. Best practices  Throw checked exception when caller can recover from error  Throw runtime exception when the caller cannot recover  Throw runtime exception for programming error  Throw early, catch late  Use NestedException  Don’t catch an exception if you cant do any thing about it.  Log exception only once, and at the latest possible time  Default Error Page in presentation layer for all Runtime Exceptions
  27. 27. Exception chaining try{ ..some code that throws XXXException }catch(XXXException ex){ throw new RuntimeException(ex); }
  28. 28. Exception logging  Log all internal states  Log all parameters to the method that failed  Log all data required to trace the error  Ensure log statements don’t cause NPE*
  29. 29. Exceptions in a typical enterprise applications  Define a hierarchy of exceptions.  Lower level module throws lower level exceptions, higher level module encapsulate lower level exceptions  Define which exceptions will cause transaction to rollback
  30. 30. Exceptions and Transactions  @ApplicationException(rollback=true) public class FooException extends Exception ...
  31. 31. Questions
  32. 32. references Best practices in EJB exception handling http://www.ibm.com/developerworks/library/j-ejbexcept.html Beware the dangers of generic Exceptions http://www.javaworld.com/javaworld/jw-10-2003/jw-1003generics.html Exception Handling in Web Applications http://weblogs.java.net/blog/crazybob/archive/2004/02/exception_han dl.html Designing with Exceptions http://www.artima.com/designtechniques/desexceptP.html Build a better exception-handling framework http://www.ibm.com/developerworks/java/library/j-ejb01283.html
  33. 33. References (cont…) JAVA EXCEPTIONS http://www.javaolympus.com/J2SE/Exceptions/JavaExceptions.jsp Exception-Handling Antipatterns http://today.java.net/pub/a/today/2006/04/06/exception-handling-antipatterns.html Three Rules for Effective Exception Handling http://today.java.net/pub/a/today/2003/12/04/exceptions.html 13 Exceptional Exception Handling Techniques http://www.manageability.org/blog/stuff/exceptional-exception-handling-techniques Best Practices for Exception Handling http://www.onjava.com/pub/a/onjava/2003/11/19/exceptions.html Lesson: Exceptions http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html

×