java exceptions best practices
DESCRIPTION
Java Exceptions Best PracticesTRANSCRIPT
Exceptions in Java
An exception is an event, which occurs during the execution of a program, that
disrupts the normal flow of the program.
Exception Hierarchy
Unchecked
CheckedError
Three Kinds of Exceptions
• Checked - subject to the Catch or Specify Requirement.• Application can recover from it.
• Errors - external to the app, app can’t recover from. • Hardware or system malfunction.
• Unchecked – not a subject to the Catch or Specify.• Application cannot recover from it. • Usually app bugs.
Exception is a part of API
Basic example
What’s Wrong Here ?
Basic example in Java 7
What else is in Java 7
Custom Exception
Exceptions in JUnit
Exceptions in JUnit
Best Practices
• Never swallow the exception in catch block.
• Always throw specific exception.
Best Practices
• Catch specific sub-classes.
• Include cause, otherwise stack trace will be lost.
Best Practices
• Either log the exception or throw it.
• Never return or throw from finally block.
Thank you!