SlideShare a Scribd company logo
1 of 33
Exception handling in java
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.
Try catch finally
try {
//do something
} catch (ExceptionType name) {
} catch (ExceptionType name) {
} finally {
//clean up
}
Advantages
 Separating Error-Handling Code from
"Regular" Code
 Propagating Errors Up the Call Stack
 Grouping and Differentiating Error
Types
Exception Type Hierarchy
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
Unchecked exceptions
 No need to declare the exception in
method’s signature
 No compile time checking
 Usually indicate programming error
 e.g. NullPointerException
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
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.
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
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
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();
}
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!
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
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
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(className);
impl =
(SomeInterface)clazz.newInstance();
}
catch (Exception e) {
log.error("Error creating class: " +
className);
}
return impl;
}
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 null;
}
 Throw
UnsupportedOperationException
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
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 trace the
error
 Ensure log statements don’t cause
NPE*
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
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 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
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

More Related Content

What's hot

Exception handling in JAVA
Exception handling in JAVAException handling in JAVA
Exception handling in JAVAKunal Singh
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handlingkamal kotecha
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in JavaJava2Blog
 
Polymorphism In Java
Polymorphism In JavaPolymorphism In Java
Polymorphism In JavaSpotle.ai
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packagesVINOTH R
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVAVINOTH R
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handlingteach4uin
 
Exceptional Handling in Java
Exceptional Handling in JavaExceptional Handling in Java
Exceptional Handling in JavaQaziUmarF786
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread SynchronizationBenj Del Mundo
 
C# Exceptions Handling
C# Exceptions Handling C# Exceptions Handling
C# Exceptions Handling sharqiyem
 
Control structures in java
Control structures in javaControl structures in java
Control structures in javaVINOTH R
 
Constructor overloading & method overloading
Constructor overloading & method overloadingConstructor overloading & method overloading
Constructor overloading & method overloadinggarishma bhatia
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPTPooja Jaiswal
 

What's hot (20)

Exception handling in JAVA
Exception handling in JAVAException handling in JAVA
Exception handling in JAVA
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Polymorphism In Java
Polymorphism In JavaPolymorphism In Java
Polymorphism In Java
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
 
Exception handling
Exception handlingException handling
Exception handling
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Java threads
Java threadsJava threads
Java threads
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
 
Exceptional Handling in Java
Exceptional Handling in JavaExceptional Handling in Java
Exceptional Handling in Java
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
 
C# Exceptions Handling
C# Exceptions Handling C# Exceptions Handling
C# Exceptions Handling
 
Control structures in java
Control structures in javaControl structures in java
Control structures in java
 
Constructor overloading & method overloading
Constructor overloading & method overloadingConstructor overloading & method overloading
Constructor overloading & method overloading
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
OOP java
OOP javaOOP java
OOP java
 
Java applet
Java appletJava applet
Java applet
 

Similar to ExceptionHandlingJava

exceptionhandlinginjava-140224181412-phpapp02.pptx
exceptionhandlinginjava-140224181412-phpapp02.pptxexceptionhandlinginjava-140224181412-phpapp02.pptx
exceptionhandlinginjava-140224181412-phpapp02.pptxARUNPRANESHS
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024nehakumari0xf
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024kashyapneha2809
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertionRakesh Madugula
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptionssaman Iftikhar
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-ivRubaNagarajan
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaKavitha713564
 
12. Exception Handling
12. Exception Handling 12. Exception Handling
12. Exception Handling Intro C# Book
 
10 Typical Enterprise Java Problems
10 Typical Enterprise Java Problems10 Typical Enterprise Java Problems
10 Typical Enterprise Java ProblemsEberhard Wolff
 
9781439035665 ppt ch11
9781439035665 ppt ch119781439035665 ppt ch11
9781439035665 ppt ch11Terry Yoast
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in JavaVadym Lotar
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overviewBharath K
 
JP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJAYAPRIYAR7
 

Similar to ExceptionHandlingJava (20)

exceptionhandlinginjava-140224181412-phpapp02.pptx
exceptionhandlinginjava-140224181412-phpapp02.pptxexceptionhandlinginjava-140224181412-phpapp02.pptx
exceptionhandlinginjava-140224181412-phpapp02.pptx
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
 
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
 
java exception.pptx
java exception.pptxjava exception.pptx
java exception.pptx
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
12. Exception Handling
12. Exception Handling 12. Exception Handling
12. Exception Handling
 
10 Typical Enterprise Java Problems
10 Typical Enterprise Java Problems10 Typical Enterprise Java Problems
10 Typical Enterprise Java Problems
 
9781439035665 ppt ch11
9781439035665 ppt ch119781439035665 ppt ch11
9781439035665 ppt ch11
 
17 exceptions
17   exceptions17   exceptions
17 exceptions
 
Exception handling
Exception handlingException handling
Exception handling
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Chap12
Chap12Chap12
Chap12
 
JP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.ppt
 
Java unit3
Java unit3Java unit3
Java unit3
 

Recently uploaded

Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 

Recently uploaded (20)

Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 

ExceptionHandlingJava

  • 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. Try catch finally try { //do something } catch (ExceptionType name) { } catch (ExceptionType name) { } finally { //clean up }
  • 4. Advantages  Separating Error-Handling Code from "Regular" Code  Propagating Errors Up the Call Stack  Grouping and Differentiating Error Types
  • 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. Unchecked exceptions  No need to declare the exception in method’s signature  No compile time checking  Usually indicate programming error  e.g. NullPointerException
  • 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. 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. 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. 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. 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. 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. 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. 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. Anti Patterns - Log and Throw  Log the error and throw the same exception again  Messy log file  Achieves nothing
  • 17. Anti Patterns - Throwing Generic Exception  The caller does not know the nature of error – hinders error handling
  • 18. Anti Patterns - Catching Generic Exception  We are masking programming errors
  • 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. Anti Patterns - Destructive Wrapping catch (NoSuchMethodException e) { throw new MyServiceException("Blah: "+ e.getMessage()); }
  • 21. Anti Patterns - Log and Return Null catch (NoSuchMethodException e) { LOG.error("Blah", e); return null; }
  • 22. Anti Patterns - Catch and Ignore (a.k.a. Head in the Sand) catch (NoSuchMethodException e) { }
  • 23. Anti Patterns - Throw from Within Finally try { blah(); } finally { cleanUp(); }
  • 24. Anti Patterns - Multi-Line Log Messages LOG.debug("Using cache policy A"); LOG.debug("Using retry policy B");
  • 25. Anti Patterns - Unsupported Operation Returning Null public String foo() { // Not supported in this implementation. return null; }  Throw UnsupportedOperationException
  • 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. Exception chaining try{ ..some code that throws XXXException }catch(XXXException ex){ throw new RuntimeException(ex); }
  • 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. 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. Exceptions and Transactions  @ApplicationException(rollback=true) public class FooException extends Exception ...
  • 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. 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

Editor's Notes

  1. Class not found Class cast to the interface SomeInterface Both types of exceptions are handled in the catch block, but that’s not evident by casual inspection of the code.