Implications of Using ExceptionsTo support exceptions and stack-unwinding, the process of calling destructors on leaving a scope, compilers put in some initialization code to ensure that if a routine may return via an exception it will properly call destructors. This seems to imply that stack-unwinding is a big part of the fixed cost regardless of whether or not you use a try/catch block. Even if you only use primitive types, if you make calls to functions, which is highly likely, then you probably end up paying this cost. So it is probably best to assume that this fixed cost is a part of the cost of a function call, and potentially, scope change if that scope change has local variables. This means there is additional code being executed. This can consist of function calls that the compiler automatically inserts into the code. Some compilers may allow this code to be generated inline to improve performance, such as C++ Builder. So if we are probably going to be paying this cost, then why worry about how many try/catch blocks there are? Because it is best to partition error handling code from regular execution code. This keeps the intent of the code clear. Another important fact about exceptions is that they affect program flow control. This is very significant particularly during the debugging process. A thrown exception can transfer control to a catch in a very distant location as well as, of course all the way up to main(). This can wreak havoc with figuring out the origin of the exception. Just consider this innocuous source listing:
Now try debugging this when an exception is generated by a function that EvenMoreFunctions() calls. And it only happens some of the time. Granted, if you're in a debugger you can just enable the 'Break on C++ Exception' option and viola. However, if this a bug report from a tester, or worse, customer, and it rarely happens, well then you have some trouble. It is not just the throw of an exception which impacts program flow control. The catch clause or more specifically, clauses can have a significant effect as well. When the exception is thrown it will be transferred to the first matching catch block of the exception type thrown. This can be conceptualized as a special kind of switch statement; and a switch statement affects flow control. |
|||||||||||