Performance Considerations for throwing Exceptions

前端 未结 8 1092
旧时难觅i
旧时难觅i 2020-12-19 03:17

I have come across the following type of code many a times, and I wonder if this is a good practice (from Performance perspective) or not:

try
{
    ... // s         


        
相关标签:
8条回答
  • 2020-12-19 04:19

    Obviously you incur in the penalty of creating new objects (the new Exception) so, exactly as you do with every line of code that you append to your program, you must to decide if the better categorization of exceptions pays for the extra work.

    As a piece of advice to make that decision, if your new objects are not carrying extra information about the exception then you can forget constructing new exceptions.

    However, in other circumstances, having a hierarchy of exceptions is very convenient for the user of your classes. Suppose you're implementing the Facade pattern neither of the so far considered scenarios is good:

    1. is not good that you raise every exception as an Exception object because you're losing (probably) valuable information
    2. is not good neither to raise every kind of object that you catch because doing so you're failing in creating the facade

    In this hypothetical case, the better thing to do is to create a hierarchy of exception classes that, abstracting your users from the inner complexities of the system, allows them to know something about the kind of exception produced.

    As a side note:

    I personally dislike the use of exceptions (hierarchies of classes derived from the Exception class) to implement logic. Like in the case:

    try {
            // something that will raise an exception almost half the time
    } catch( InsufficientFunds e) {
            // Inform the customer is broke
    } catch( UnknownAccount e ) {
            // Ask for a new account number
    }
    
    0 讨论(0)
  • 2020-12-19 04:22

    From a purely performance stand-point I'd guess that the third case is most performant. The other two need to extract a stack-trace and construct new objects, both of which are potentially fairly time-consuming.

    Having said that these three blocks of code have very different (external) behaviors so comparing them is like asking whether QuickSort is more efficient than Adding an item to a red-black tree. It's not as important as selecting the right thing to do.

    0 讨论(0)
提交回复
热议问题