Monday, October 4, 2010

Exception Handling Principles

1.  System.out.println is expensive. These calls are synchronized for the duration of disk I/O, which

significantly slows throughput.

2. By default, stack traces are logged to the console. But browsing the console for an exception trace isn't feasible in

a production system.

3. In addition, they aren't guaranteed to show up in the production system, because system administrators can map

System.out and System.errs to ' ' [>nul] on NT and dev/nul on UNIX. Moreover, if you're running the

J2EE app server as an NT service, you won't even have a console.

4. Even if you redirect the console log to an output file, chances are that the file will be overwritten when the

production J2EE app servers are restarted.

5. Using System.out.println during testing and then removing them before production isn't an elegant solution

either, because doing so means your production code will not function the same as your test code.

6. If you can't handle an exception, don't catch it.

7. Catch an exception as close as possible to its source.

8. If you catch an exception, don't swallow it.

9. Log an exception where you catch it, unless you plan to re-throw it.

10. Preserve the stack trace when you re-throw the exception by wrapping the original exception in the new one.

11. Use as many typed exceptions as you need, particularly for application exceptions. Do not just use

java.lang.Exception every time you need to declare a throws clause. By fine graining the throws clause, it is self-

documenting and becomes evident to the caller that different exceptions have to be handled.

12. If you programming application logic, use unchecked exceptions to indicate an error from which the user cannot

recover. If you are creating third party libraries to be used by other developers, use checked exceptions for

unrecoverable errors too.

13. Never throw unchecked exceptions in your methods just because it clutters the method signature. There are some

scenarios where this is good (For e.g. EJB Interface/Implementations, where unchecked exceptions alter the bean

behavior in terms of transaction commit and rollback), but otherwise this is not a good practice.

14. Throw Application Exceptions as Unchecked Exceptions and Unrecoverable System exceptions as unchecked

exceptions.

15. Structure your methods according to how fine-grained your exception handling must be.