java exceptions best practices

16
Exceptions in Java

Upload: artur-mkrtchyan

Post on 15-Jan-2015

206 views

Category:

Software


3 download

DESCRIPTION

Java Exceptions Best Practices

TRANSCRIPT

Page 1: Java Exceptions Best Practices

Exceptions in Java

Page 2: Java Exceptions Best Practices

An exception is an event, which occurs during the execution of a program, that

disrupts the normal flow of the program.

Page 3: Java Exceptions Best Practices

Exception Hierarchy

Unchecked

CheckedError

Page 4: Java Exceptions Best Practices

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.

Page 5: Java Exceptions Best Practices

Exception is a part of API

Page 6: Java Exceptions Best Practices

Basic example

Page 7: Java Exceptions Best Practices

What’s Wrong Here ?

Page 8: Java Exceptions Best Practices

Basic example in Java 7

Page 9: Java Exceptions Best Practices

What else is in Java 7

Page 10: Java Exceptions Best Practices

Custom Exception

Page 11: Java Exceptions Best Practices

Exceptions in JUnit

Page 12: Java Exceptions Best Practices

Exceptions in JUnit

Page 13: Java Exceptions Best Practices

Best Practices

• Never swallow the exception in catch block.

• Always throw specific exception.

Page 14: Java Exceptions Best Practices

Best Practices

• Catch specific sub-classes.

• Include cause, otherwise stack trace will be lost.

Page 15: Java Exceptions Best Practices

Best Practices

• Either log the exception or throw it.

• Never return or throw from finally block.

Page 16: Java Exceptions Best Practices

Thank you!