开发者

Reading exception from try catch when exception type not specified

In cases when you use a try catch block as such.

try {
    //Do my work!
} 
catch 
{
    //Handle my exception
}

Is there some w开发者_Go百科ay to refer to the exception object in the catch block?

ie:

try {
    //Do my work!
} 
catch 
{
    //Handle my exception
    MyUndefinedExceptionObject.Message ????
}

EDIT: I don't think I was clear enough. I am aware of how one would typically catch exceptions using a try catch block. What I am wondering is given you have the ability to not specify a type for your exception yet declare the block is there still some way of retrieving the exception object in such cases? Judging by your answers however I assume there isn't?


You'll want to catch the exception type you care about. When you do, you'll have access to all the properties of that exception.

try
{
    //Do my work!
} 
catch (MyExceptionType e)
{
   string s = e.Message;
}

Here's a reference in MSDN, to get up to speed.

Regarding your edit: no there is no way to access the thrown exception unless the exception is explicitly specified in your catch statement.


Yes, like this:

try 
{
    //Do my work!
} 
catch (mySpecificException myEx)
{
    //Handle my exception
}
catch (Exception ex)
{
    //Handle my exception
}

(Most specific to least specific)


No.

Using the bare catch indicates that you do not care about the actual exception otherwise, why not use

catch (System.Exception ex)

to catch any exception? Of course, you should only catch exceptions you will handle.


You need to indicate the specific type of exception that you are catching, and assign that to a variable.

Do that using this syntax instead:

try 
{
    // Do work
}
catch (MyUndefinedExceptionObject ex)
{
    Debug.WriteLine(ex.Message);
}

You can also include multiple catch blocks with the type of exception altered accordingly. However, remember that you should always order them from most derived to least derived, ending with the base class for all exceptions, System.Exception.

You also should generally refrain from catching System.Exception, instead preferring only to catch the derived exceptions that you can handle in the catch block and that won't corrupt your program's state. Catching System.Exception class is a bad idea because you'll also catch exceptions that you won't be able to handle, like an OutOfMemoryException or a StackOverflowException.

Microsoft has a helpful article on best practices here: Best Practices for Handling Exceptions

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜