Information Technology Reference
In-Depth Information
throw new DoingSomeWorkException(msg, e);
}
}
}
This new version creates more information at the point where the prob-
lem is generated. As long as you have created a proper ToString() method
(see Item 5), you've created an exception that describes the complete state
of the object that generated the problem. More than that, the inner excep-
tion shows the root cause of the problem: something in the third-party
library you used.
This technique is called exception translation, translating a low-level
exception into a more high-level exception that provides more context
about the error. The more information you generate when an error occurs,
the easier it will be for users to diagnose and possibly correct the error. By
creating your own exception types, you can translate low-level generic
problems into specific exceptions that contain all the application-specific
information that you need to fully diagnose and possibly correct the
problem.
Yo u r a p p l i c a t i o n w i l l t h r o w e x c e p t i o n s — h o p e f u l l y n o t o f t e n , b u t i t w i l l
happen. If you don't do anything specific, your application will generate
the default .NET Framework exceptions whenever something goes wrong
in the methods you call on the core framework. Providing more detailed
information will go a long way to enabling you and your users to diagnose
and possibly correct errors in the field. You create different exception
classes when different corrective actions are possible and only when dif-
ferent actions are possible. You create full-featured exception classes by
providing all the constructors that the base exception class supports. You
use the InnerException property to carry along all the error information
generated by lower-level error conditions.
Item 47: Prefer the Strong Exception Guarantee
When you throw an exception, you've introduced a disruptive event into
the application. Control flow has been compromised. Expected actions did
not occur. Worse, you've left the cleanup operation to the programmer
writing the code that eventually catches the exception. The actions avail-
able when you catch exceptions are directly related to how well you man-
age program state when an exception gets thrown. Thankfully, the C#
 
 
Search WWH ::




Custom Search