Exception handling in java
-
Upload
pratik-soares -
Category
Technology
-
view
1.224 -
download
8
description
Transcript of Exception handling in java
![Page 1: Exception handling in java](https://reader033.fdocuments.in/reader033/viewer/2022061512/555c3cedd8b42a2c068b4ad5/html5/thumbnails/1.jpg)
Exception handling in java
![Page 2: Exception handling in java](https://reader033.fdocuments.in/reader033/viewer/2022061512/555c3cedd8b42a2c068b4ad5/html5/thumbnails/2.jpg)
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.
![Page 3: Exception handling in java](https://reader033.fdocuments.in/reader033/viewer/2022061512/555c3cedd8b42a2c068b4ad5/html5/thumbnails/3.jpg)
Try catch finally
try { //do something} catch (ExceptionType name) { } catch (ExceptionType name) { } finally {
//clean up}
![Page 4: Exception handling in java](https://reader033.fdocuments.in/reader033/viewer/2022061512/555c3cedd8b42a2c068b4ad5/html5/thumbnails/4.jpg)
Advantages
Separating Error-Handling Code from "Regular" Code
Propagating Errors Up the Call Stack
Grouping and Differentiating Error Types
![Page 5: Exception handling in java](https://reader033.fdocuments.in/reader033/viewer/2022061512/555c3cedd8b42a2c068b4ad5/html5/thumbnails/5.jpg)
Exception Type Hierarchy
![Page 6: Exception handling in java](https://reader033.fdocuments.in/reader033/viewer/2022061512/555c3cedd8b42a2c068b4ad5/html5/thumbnails/6.jpg)
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
![Page 7: Exception handling in java](https://reader033.fdocuments.in/reader033/viewer/2022061512/555c3cedd8b42a2c068b4ad5/html5/thumbnails/7.jpg)
Unchecked exceptions
No need to declare the exception in method’s signature
No compile time checking Usually indicate programming
error e.g. NullPointerException
![Page 8: Exception handling in java](https://reader033.fdocuments.in/reader033/viewer/2022061512/555c3cedd8b42a2c068b4ad5/html5/thumbnails/8.jpg)
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
![Page 9: Exception handling in java](https://reader033.fdocuments.in/reader033/viewer/2022061512/555c3cedd8b42a2c068b4ad5/html5/thumbnails/9.jpg)
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.
![Page 10: Exception handling in java](https://reader033.fdocuments.in/reader033/viewer/2022061512/555c3cedd8b42a2c068b4ad5/html5/thumbnails/10.jpg)
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
![Page 11: Exception handling in java](https://reader033.fdocuments.in/reader033/viewer/2022061512/555c3cedd8b42a2c068b4ad5/html5/thumbnails/11.jpg)
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
![Page 12: Exception handling in java](https://reader033.fdocuments.in/reader033/viewer/2022061512/555c3cedd8b42a2c068b4ad5/html5/thumbnails/12.jpg)
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();}
![Page 13: Exception handling in java](https://reader033.fdocuments.in/reader033/viewer/2022061512/555c3cedd8b42a2c068b4ad5/html5/thumbnails/13.jpg)
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!
![Page 14: Exception handling in java](https://reader033.fdocuments.in/reader033/viewer/2022061512/555c3cedd8b42a2c068b4ad5/html5/thumbnails/14.jpg)
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
![Page 15: Exception handling in java](https://reader033.fdocuments.in/reader033/viewer/2022061512/555c3cedd8b42a2c068b4ad5/html5/thumbnails/15.jpg)
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
![Page 16: Exception handling in java](https://reader033.fdocuments.in/reader033/viewer/2022061512/555c3cedd8b42a2c068b4ad5/html5/thumbnails/16.jpg)
Anti Patterns - Log and Throw
Log the error and throw the same exception again
Messy log file Achieves nothing
![Page 17: Exception handling in java](https://reader033.fdocuments.in/reader033/viewer/2022061512/555c3cedd8b42a2c068b4ad5/html5/thumbnails/17.jpg)
Anti Patterns - Throwing Generic Exception
The caller does not know the nature of error – hinders error handling
![Page 18: Exception handling in java](https://reader033.fdocuments.in/reader033/viewer/2022061512/555c3cedd8b42a2c068b4ad5/html5/thumbnails/18.jpg)
Anti Patterns - Catching Generic Exception
We are masking programming errors
![Page 19: Exception handling in java](https://reader033.fdocuments.in/reader033/viewer/2022061512/555c3cedd8b42a2c068b4ad5/html5/thumbnails/19.jpg)
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;}
![Page 20: Exception handling in java](https://reader033.fdocuments.in/reader033/viewer/2022061512/555c3cedd8b42a2c068b4ad5/html5/thumbnails/20.jpg)
Anti Patterns - Destructive Wrapping
catch (NoSuchMethodException e) { throw new
MyServiceException("Blah: " + e.getMessage());}
![Page 21: Exception handling in java](https://reader033.fdocuments.in/reader033/viewer/2022061512/555c3cedd8b42a2c068b4ad5/html5/thumbnails/21.jpg)
Anti Patterns - Log and Return Null
catch (NoSuchMethodException e) { LOG.error("Blah", e); return null;}
![Page 22: Exception handling in java](https://reader033.fdocuments.in/reader033/viewer/2022061512/555c3cedd8b42a2c068b4ad5/html5/thumbnails/22.jpg)
Anti Patterns - Catch and Ignore (a.k.a. Head in the Sand)
catch (NoSuchMethodException e) {}
![Page 23: Exception handling in java](https://reader033.fdocuments.in/reader033/viewer/2022061512/555c3cedd8b42a2c068b4ad5/html5/thumbnails/23.jpg)
Anti Patterns - Throw from Within Finally
try { blah();} finally { cleanUp();}
![Page 24: Exception handling in java](https://reader033.fdocuments.in/reader033/viewer/2022061512/555c3cedd8b42a2c068b4ad5/html5/thumbnails/24.jpg)
Anti Patterns - Multi-Line Log Messages
LOG.debug("Using cache policy A");
LOG.debug("Using retry policy B");
![Page 25: Exception handling in java](https://reader033.fdocuments.in/reader033/viewer/2022061512/555c3cedd8b42a2c068b4ad5/html5/thumbnails/25.jpg)
Anti Patterns - Unsupported Operation Returning Null
public String foo() { // Not supported in this
implementation. return null;}
Throw UnsupportedOperationException
![Page 26: Exception handling in java](https://reader033.fdocuments.in/reader033/viewer/2022061512/555c3cedd8b42a2c068b4ad5/html5/thumbnails/26.jpg)
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
![Page 27: Exception handling in java](https://reader033.fdocuments.in/reader033/viewer/2022061512/555c3cedd8b42a2c068b4ad5/html5/thumbnails/27.jpg)
Exception chaining
try{ ..some code that throws
XXXException }catch(XXXException ex){ throw new
RuntimeException(ex); }
![Page 28: Exception handling in java](https://reader033.fdocuments.in/reader033/viewer/2022061512/555c3cedd8b42a2c068b4ad5/html5/thumbnails/28.jpg)
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*
![Page 29: Exception handling in java](https://reader033.fdocuments.in/reader033/viewer/2022061512/555c3cedd8b42a2c068b4ad5/html5/thumbnails/29.jpg)
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
![Page 30: Exception handling in java](https://reader033.fdocuments.in/reader033/viewer/2022061512/555c3cedd8b42a2c068b4ad5/html5/thumbnails/30.jpg)
Exceptions and Transactions
@ApplicationException(rollback=true) public class FooException extends Exception ...
![Page 31: Exception handling in java](https://reader033.fdocuments.in/reader033/viewer/2022061512/555c3cedd8b42a2c068b4ad5/html5/thumbnails/31.jpg)
Questions
![Page 32: Exception handling in java](https://reader033.fdocuments.in/reader033/viewer/2022061512/555c3cedd8b42a2c068b4ad5/html5/thumbnails/32.jpg)
referencesBest practices in EJB exception handlinghttp://www.ibm.com/developerworks/library/j-ejbexcept.html
Beware the dangers of generic Exceptionshttp://www.javaworld.com/javaworld/jw-10-2003/jw-1003-
generics.html
Exception Handling in Web Applicationshttp://weblogs.java.net/blog/crazybob/archive/2004/02/
exception_handl.html
Designing with Exceptionshttp://www.artima.com/designtechniques/desexceptP.html
Build a better exception-handling frameworkhttp://www.ibm.com/developerworks/java/library/j-
ejb01283.html
![Page 33: Exception handling in java](https://reader033.fdocuments.in/reader033/viewer/2022061512/555c3cedd8b42a2c068b4ad5/html5/thumbnails/33.jpg)
References (cont…)JAVA EXCEPTIONS http://www.javaolympus.com/J2SE/Exceptions/JavaExceptions.jsp
Exception-Handling Antipatternshttp://today.java.net/pub/a/today/2006/04/06/exception-handling-
antipatterns.html
Three Rules for Effective Exception Handlinghttp://today.java.net/pub/a/today/2003/12/04/exceptions.html
13 Exceptional Exception Handling Techniqueshttp://www.manageability.org/blog/stuff/exceptional-exception-handling-
techniques
Best Practices for Exception Handlinghttp://www.onjava.com/pub/a/onjava/2003/11/19/exceptions.html
Lesson: Exceptionshttp://java.sun.com/docs/books/tutorial/essential/exceptions/index.html