August 02, 2006
Mandatory Error Codes RevisitedForcing the use of error codesGuy Peleg
Mandatory error codes force callers of a method to accept and use the returned error code.
Guy is chief architect of event processing for the Amdocs Billing Platform (http://www.amdocs.com). He can be contacted at guy.peleg@amdocs.com.
In his article "Three Ideas" (http://www.ddj.com/dept/cpp/184401917), Andrei Alexandrescu described a framework for "mandatory error codes" that forces callers of a method to accept and use the returned error code. In this article, I refer to these codes as "forcing methods."
The idea is simple, yet powerful: A template class ErrorCode, which holds the real error code, is returned from a forcing method. When the returned ErrorCode goes out of scope, it throws an exceptionunless the caller uses the error code (using the cast operator). The caller can explicitly ignore the error code by casting the ErrorCode with IgnoreError. Listing One presents the classes that make up this framework, while Example 1 shows how you can use it.
Listing One
ErrorCode<int> FallableFunction(); // function declaration
ErrorCode<int> result = FallableFunction(); // ok
if (FallableFunction ()) {...} // ok
FallableFunction(); // will throw
(IgnoreError) FallableFunction(); // ok
Example 1: Using the framework.
However, the problem with this framework is the exception that might be thrown at the destructor of ErrorCode. For instance, Example 2 looks perfectly normal. You don't ignore the returned error codes; you accept and use them. There's even a special recover method that can handle everything. Well, almost everything.
void AClass::someMethod()
{
try {
ErrorCode<int> ec1 = this->fallableMethod_1();
ErrorCode<int> ec2 = this->fallableMethod_2();
if (ec1 && ec2) {
this->doSomething();
}
}
catch (...) {
this->recover();
}
}
Example 2: Problem code.
Here's the problem: If this->fallableMethod_2() throws, then the ec1 destructor is activated. But since no one has yet used ec1, another exception is thrown (from activating ec1's destructor), which terminates the process (set_terminate is called but this won't help). This is a big surprise if you've followed all the rules.
|
|
||||||||||||||||||||||||||||||
|
|
|
|