On Exceptions

  • Try to avoid exceptions. Use the language features and proper design in order to achieve it.
  • Use runtime exceptions, wrap methods with checked exceptions and turn them in at runtime.
  • Try to use standard exceptions.
  • Make your exceptions specific and descriptive.
  • Catch the most specific exception first.
  • Do not catch on Exception.
  • But catch on Exception on the boundaries of your API. Have complete control over what comes out to the world.
  • Create a hierarchy of exceptions that match the layers and functionalities of your application.
  • Throw exceptions at the proper abstraction level. Catch an exception and throw a higher level one as you move from layer to layer.
  • Pass the complete history of exceptions when rethrowing by providing the exception in the constructor of the new one.
  • Think of the try-catch-finally block as a transaction. Make sure you leave your program in a valid state when something goes wrong.
  • Catch exceptions when you can handle it.
  • Never have empty catch clauses.
  • Log an exception when you handle it.
  • Have a global exception handling service and have a strategy on how you handle errors.

To view or add a comment, sign in

More articles by Mojtaba Nasehzadeh

  • SpringBootTest vs. WebMvcTest

    Spring Boot provides a @SpringBootTest annotation that works by creating the ApplicationContext used in your tests…

  • Aggregate Pattern

    Problem Imagine that you’re writing yet another e-commerce application and you’re tasked with writing the all-important…

  • Guidelines for Java Testable Design

    Issues with testability boil down to our inability to write tests or the excess trouble we have to go through to get it…

  • Processing Large XML Files with Java

    When processing XML data it's usually most convenient to load the whole document using a DOMparser and fire some…

  • Java Application Performance

    How to define measurable performance goals Different tools to measure and monitor application performance Identify…

  • Should You Use JSF for New Projects?

    There was an excellent StackOverflow blog post last week about the “Brutal Lifecycle of JavaScript Frameworks”. The…

    1 Comment
  • Code Review

    Learning to write code that is Safe from bugs Easy to understand Ready for change Code review is careful, systematic…

  • Spring Batch Pattern: Passing Data to Future Steps

    It is often useful to pass information from one step to another. This can be done using the ExecutionContext.

    1 Comment
  • ORA-04030

    Error ORA-04030 occurs when the system cannot allocate any more PGA(Program or Process Global Area) memory. This…

  • Understanding Hibernate Transaction Flush Mode

    What is Transaction Flush Mode Hibernate does not flush every add or update transaction to the database. Rather…

    2 Comments

Explore content categories