简体   繁体   中英

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 way 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM