SlideShare a Scribd company logo
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

PPSX
Exception Handling
Reddhi Basu
 
PPTX
Exception handling in java
Elizabeth alexander
 
PDF
Java exception handling ppt
JavabynataraJ
 
PPTX
Exceptionhandling
Nuha Noor
 
PPT
Exception Handling in JAVA
SURIT DATTA
 
PPTX
Exception handling in java
ARAFAT ISLAM
 
PPTX
Exceptions in Java
Vadym Lotar
 
Exception Handling
Reddhi Basu
 
Exception handling in java
Elizabeth alexander
 
Java exception handling ppt
JavabynataraJ
 
Exceptionhandling
Nuha Noor
 
Exception Handling in JAVA
SURIT DATTA
 
Exception handling in java
ARAFAT ISLAM
 
Exceptions in Java
Vadym Lotar
 

What's hot (20)

PPTX
Exception Handling in Java
lalithambiga kamaraj
 
PDF
Constants, Variables and Data Types in Java
Abhilash Nair
 
PPT
Exception handling
Tata Consultancy Services
 
PPTX
Java basics and java variables
Pushpendra Tyagi
 
PPTX
Control structures in java
VINOTH R
 
PPT
C# Exceptions Handling
sharqiyem
 
PPTX
L14 exception handling
teach4uin
 
PPTX
Java exception handling
BHUVIJAYAVELU
 
PPTX
Array in Java
Ali shah
 
PPTX
Exception handling in Java
Abhishek Pachisia
 
PDF
Introduction to Java Programming
Ravi Kant Sahu
 
PPT
Java interfaces
Raja Sekhar
 
PPTX
Data Types, Variables, and Operators
Marwa Ali Eissa
 
PPT
9. Input Output in java
Nilesh Dalvi
 
PPT
Core java concepts
Ram132
 
PPT
Looping statements in Java
Jin Castor
 
PPTX
Java program structure
shalinikarunakaran1
 
PPTX
Java - Generic programming
Riccardo Cardin
 
PPTX
Static Data Members and Member Functions
MOHIT AGARWAL
 
PPTX
Type casting in java
Farooq Baloch
 
Exception Handling in Java
lalithambiga kamaraj
 
Constants, Variables and Data Types in Java
Abhilash Nair
 
Exception handling
Tata Consultancy Services
 
Java basics and java variables
Pushpendra Tyagi
 
Control structures in java
VINOTH R
 
C# Exceptions Handling
sharqiyem
 
L14 exception handling
teach4uin
 
Java exception handling
BHUVIJAYAVELU
 
Array in Java
Ali shah
 
Exception handling in Java
Abhishek Pachisia
 
Introduction to Java Programming
Ravi Kant Sahu
 
Java interfaces
Raja Sekhar
 
Data Types, Variables, and Operators
Marwa Ali Eissa
 
9. Input Output in java
Nilesh Dalvi
 
Core java concepts
Ram132
 
Looping statements in Java
Jin Castor
 
Java program structure
shalinikarunakaran1
 
Java - Generic programming
Riccardo Cardin
 
Static Data Members and Member Functions
MOHIT AGARWAL
 
Type casting in java
Farooq Baloch
 
Ad

Viewers also liked (6)

PPTX
Coeducation
skmaken
 
PPT
Java exception
Arati Gadgil
 
PPTX
Effects of TECHNOLOGY
Amna Kazim
 
PPS
Java Exception handling
kamal kotecha
 
PPT
Impact of Fast Food
Manpreet Singh Bedi
 
PPTX
Corruption in pakistan
Riaz Gul Sheikh
 
Coeducation
skmaken
 
Java exception
Arati Gadgil
 
Effects of TECHNOLOGY
Amna Kazim
 
Java Exception handling
kamal kotecha
 
Impact of Fast Food
Manpreet Singh Bedi
 
Corruption in pakistan
Riaz Gul Sheikh
 
Ad

Similar to Exception handling in java (20)

PPTX
exceptionhandlinginjava-140224181412-phpapp02.pptx
ARUNPRANESHS
 
PPTX
Introduction to java exceptions
Sujit Kumar
 
PPTX
Training material exceptions v1
Shinu Suresh
 
PPT
Exception handling
pooja kumari
 
PPT
Exceptions in java
Manav Prasad
 
PPTX
presentationon exception handling in java.pptx
LubnaJavedMansuri
 
PPT
Exception Handling
PRN USM
 
PPT
exceptions in java
javeed_mhd
 
PPT
JP ASSIGNMENT SERIES PPT.ppt
JAYAPRIYAR7
 
PPT
06 exceptions
Waheed Warraich
 
PPT
Java: Exception
Tareq Hasan
 
PDF
Exception Handling.pdf
lsdfjldskjf
 
PDF
Exception handling
Garuda Trainings
 
PDF
Exception handling
Garuda Trainings
 
PDF
Java exception-handling
Suresh Kumar Reddy V
 
PPSX
Java Exceptions
jalinder123
 
PPSX
Java Exceptions Handling
DrRajeshreeKhande
 
PDF
Class notes(week 8) on exception handling
Kuntal Bhowmick
 
PPTX
130410107010 exception handling
Hemant Chetwani
 
PPTX
Exception handling
Minal Maniar
 
exceptionhandlinginjava-140224181412-phpapp02.pptx
ARUNPRANESHS
 
Introduction to java exceptions
Sujit Kumar
 
Training material exceptions v1
Shinu Suresh
 
Exception handling
pooja kumari
 
Exceptions in java
Manav Prasad
 
presentationon exception handling in java.pptx
LubnaJavedMansuri
 
Exception Handling
PRN USM
 
exceptions in java
javeed_mhd
 
JP ASSIGNMENT SERIES PPT.ppt
JAYAPRIYAR7
 
06 exceptions
Waheed Warraich
 
Java: Exception
Tareq Hasan
 
Exception Handling.pdf
lsdfjldskjf
 
Exception handling
Garuda Trainings
 
Exception handling
Garuda Trainings
 
Java exception-handling
Suresh Kumar Reddy V
 
Java Exceptions
jalinder123
 
Java Exceptions Handling
DrRajeshreeKhande
 
Class notes(week 8) on exception handling
Kuntal Bhowmick
 
130410107010 exception handling
Hemant Chetwani
 
Exception handling
Minal Maniar
 

Recently uploaded (20)

PPTX
C Programming Basics concept krnppt.pptx
Karan Prajapat
 
PDF
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PDF
Why Your AI & Cybersecurity Hiring Still Misses the Mark in 2025
Virtual Employee Pvt. Ltd.
 
PDF
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
PDF
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
PDF
Enable Enterprise-Ready Security on IBM i Systems.pdf
Precisely
 
PDF
NewMind AI Monthly Chronicles - July 2025
NewMind AI
 
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
AVTRON Technologies LLC
 
PDF
Google’s NotebookLM Unveils Video Overviews
SOFTTECHHUB
 
PDF
agentic-ai-and-the-future-of-autonomous-systems.pdf
siddharthnetsavvies
 
PDF
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
PDF
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
PPTX
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
PDF
Software Development Company | KodekX
KodekX
 
PDF
This slide provides an overview Technology
mineshkharadi333
 
PDF
REPORT: Heating appliances market in Poland 2024
SPIUG
 
PDF
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
C Programming Basics concept krnppt.pptx
Karan Prajapat
 
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
Why Your AI & Cybersecurity Hiring Still Misses the Mark in 2025
Virtual Employee Pvt. Ltd.
 
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
Enable Enterprise-Ready Security on IBM i Systems.pdf
Precisely
 
NewMind AI Monthly Chronicles - July 2025
NewMind AI
 
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
AVTRON Technologies LLC
 
Google’s NotebookLM Unveils Video Overviews
SOFTTECHHUB
 
agentic-ai-and-the-future-of-autonomous-systems.pdf
siddharthnetsavvies
 
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
Software Development Company | KodekX
KodekX
 
This slide provides an overview Technology
mineshkharadi333
 
REPORT: Heating appliances market in Poland 2024
SPIUG
 
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 

Exception handling in java

  • 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

  • #21: 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.