Performance cost of coding “exception driven development” in Java?

前端 未结 14 1670
生来不讨喜
生来不讨喜 2020-12-09 10:28

Are there are any performance cost by creating, throwing and catching exceptions in Java?

I am planing to add \'exception driven development\' into a larger project.

14条回答
  •  遥遥无期
    2020-12-09 11:10

    I like this style of coding as it makes it very clear about what is going on from the point of view of someone using your API. I sometimes even name API methods getMandatoryUser(String) and getUserOrNull(String) to distinguish between methods that will never return null and those which can return null.

    Regarding performance unless you're writing a very latency critical piece of code the performance overhead will be negligable. However, it's worth mentioning there are some best practices when it comes to try / catch blocks. For example, I believe Effective Java advocates creating a try / catch block outside of a loop to avoid creating it on each iteration; e.g.

    boolean done = false;
    
    // Initialise loop counter here to avoid resetting it to 0 if an Exception is thrown.
    int i=0;    
    
    // Outer loop: We only iterate here if an exception is thrown from the inner loop.
    do {
      // Set up try-catch block.  Only done once unless an exception is thrown.    
      try {
        // Inner loop: Does the actual work.
        for (; i<1000000; ++i) {
          // Exception potentially thrown here.
        }
    
        done = true;
      } catch(Exception ex) {
        ... 
      }
    } while (!done);
    

提交回复
热议问题