Performance Considerations for throwing Exceptions

前端 未结 8 1114
旧时难觅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
    }
    

提交回复
热议问题