Game Development Reference
In-Depth Information
Lastly, one of the absolute worst things you can do is catch an exception and do
nothing with it. Catching an exception with an empty code block is commonly
referred to as exception swallowing ; do not do this! If you do not wish to handle a
certain type of exception, don't write an exception handler for it.
Logging Exception Information
At first glance, it may look correct to spit out the contents of Exception.Message to
whatever logging medium you are using, but such an assumption would be incor-
rect. The Exception.Message property only contains the high-level message, which
could be as informative as Object reference not set to an instance of an object .
A better approach instead is to log Exception.ToString() , which will result in the
logging of the message, the inner exception, and the stack trace of the exception—
information that is much more useful when it comes time to debug a problem.
Mechanisms for Cleanup
There are a number of classes in the .NET class framework that require cleanup
after their role has been fulfilled, and certain classes (like file system access) can
lead to locking or other problems when not properly disposed.
Consider the following code:
public void DoSomething(string fileName)
{
StreamReader reader = new StreamReader(string fileName);
ProcessStream(reader);
reader.Close();
}
All is well if no errors occur, but consider the situation where ProcessStream throws
an exception. The close method for the StreamReader would never be called, and the
resource would remain active.
One solution to this problem is to introduce an exception handler that closes the
StreamReader when an error occurs, and then re-throws the exception.
Consider the following code:
public void DoSomething(string fileName)
{
StreamReader reader = null;
try
{
Search Nedrilad ::




Custom Search