23
Best Practices Exception Handling Abid Hossain Khan

Coding best practices_exception handling

Embed Size (px)

Citation preview

Page 1: Coding best practices_exception handling

Best PracticesException Handling

Abid Hossain Khan

Page 2: Coding best practices_exception handling

Agenda

Advantages

Exception Hierarchy

Best Practices

Page 3: Coding best practices_exception handling

Advantages

Represent a meaningful message to user

Log unhandled exception once and only once

Correlate exceptions with unique request id (session) in log file for high precision debugging

Implement powerful but extensible exception handling strategy for each tiers

Page 4: Coding best practices_exception handling

Exception Hierarchy

Page 5: Coding best practices_exception handling

Best Practice : 1

Never swallow exception in catch block

Page 6: Coding best practices_exception handling

Best Practice : 2

Declare the specific checked exceptions that your method can throw

Page 7: Coding best practices_exception handling

Best Practice : 3

Do not catch the Exception class rather catch specific sub classes

Page 8: Coding best practices_exception handling

Best Practice : 4

• Never catch Throwable class

Page 9: Coding best practices_exception handling

Best Practice : 5

Always correctly wrap the exceptions in custom exceptions so that stack trace is not lost

Page 10: Coding best practices_exception handling

Best Practice : 6

Either log the exception or throw it but never do the both

Page 11: Coding best practices_exception handling

Best Practice : 7

Never throw any exception from finally block

Page 12: Coding best practices_exception handling

Best Practice : 8

Always catch only those exceptions that you can actually handle

Page 13: Coding best practices_exception handling

Best Practice : 9

Don’t use printStackTrace() statement or similar methods

Page 14: Coding best practices_exception handling

Best Practice : 10

Use finally blocks instead of catch blocks if you are not going to handle exception

Page 15: Coding best practices_exception handling

Best Practice : 11

Throw early catch late

Page 16: Coding best practices_exception handling

Best Practice : 12

Always clean up after handling the exception

Page 17: Coding best practices_exception handling

Best Practice : 13

• Throw only relevant exception from a method

Page 18: Coding best practices_exception handling

Best Practice : 14

Never use exceptions for flow control in your program

Page 19: Coding best practices_exception handling

Best Practice : 15

Always include all information about an exception in single log message

Page 20: Coding best practices_exception handling

Best Practice : 16

Use template methods for repeated try-catch

Page 21: Coding best practices_exception handling

Best Practice : 17

Document all exceptions in your application in javadoc

Page 22: Coding best practices_exception handling
Page 23: Coding best practices_exception handling

Thank You