Error Handling

Two types of exceptions

  • Expected or business exceptions ~ checked?

  • Unexpected program or environment errors ~ unchecked?

Good Practices

  • Prefer exceptions to return codes - decreases pollution of clients

  • Prefer exception types to exception payload - error codes

  • Provide context for exception:

    • chain exceptions when wrapping

    • add erroneous object(s)

  • Do not return null - throw exception (e.g. IllegalArgumentException)

  • Prefer runtime exceptions to checked exceptions - decreases pollution and dependency

  • Wrap exceptions in module or service specific exceptions - decrease dependency

  • Only unexpected exceptions should be logged on error level with stack-trace.

Bad Practices

  • Swallow exceptions

  • Implement business logic in catch block

  • Do not catch exceptions unless you handle them

  • handleError() type of methods -

    • not readable what they do

    • they cheat the compiler too

Last updated