C# question - how to populate a catch statement with the specific possible exceptions from the code in the try?
I'm using VS2008 and have ReSharper too.
My question is how can I automate the creation of a try/catch block for which the catch is specifically populated with the possible exception from the try block? (i.e. not just put开发者_Python百科 in an Exception ex)
Background - Trying to help follow the best practice I read of "Don't catch (Exception) more than once per thread. Good code throws exceptions as needed, and handles only the exceptions it knows how to handle."
thanks
To do that I think you would need a tool that recursively walks your code (and the code it calls, and so forth), and figures out which exceptions could possibly be thrown.
Redgate has a tool that does this. However, I think you probably have a fair idea in your code of what possible exceptions it might throw, and the BCL has decent documentation that says what exceptions might possibly be thrown by any given method you call in the BCL, so it's probably not too hard at the local level to figure out what you need to handle and what you don't.
From what I've read, this was one of the major reasons why the C# team chose not to implement checked exceptions similar to Java - they wanted to discourage this kind of exception non-handling.
There is no means of intrinsically automating such an operation in Visual Studio, nor should you try; if you don't know how to handle a particular exception, then don't catch it just because the library might throw it.
In addition, there are all sorts of special-case system exceptions that might be thrown by the framework, like OutOfMemoryException
, BadImageFormatException
, AppDomainUnloadedException
and so on, that aren't directly thrown by the particular method you're invoking but bubble through it from the .NET runtime. If you wanted to catch all possible exceptions then you'd have to catch these as well, but for the most part it would be a fruitless exercise since there's not much you can do when you get a StackOverflowException
- and again, you generally shouldn't attempt to.
In conclusion, the best way to write exception handlers for library methods (and any other methods) is to read the documentation on said method, which will tell you what exceptions you can expect it to throw, and then catch only the ones you actually expect and/or know how to handle. Do not catch the generic System.Exception
unless you want spectacular crashes and mysterious data corruption late into the production cycle.
精彩评论