Suppose I have a library that uses exceptions to indicate success or failure.
I expect the exceptions to be thrown a lot of times when I try requesting different properties of this library.
Now in .NET, it is said that开发者_JAVA技巧 try
ing costs nothing, but catch
ing does. (Exception handling cost is in the exceptional case).
Is there a way to tell .NET to put the cost in installing the handler? Like in C++?
Clarifying: the calling code 'iterates' over all possible function argument values:
foreach( var enumvalue in Enum.GetValues( MyEnum ) ) {
try {
libraryObject.libFunction( enumvalue ); // will probably throw...
} catch(ArgumentException) {
}
}
Note: I know this is not a great API. It should be extended in order to iterate over the 'possible' values, or to work with return codes. I don't need answers that restate that.
I don't think there is a way to make exceptions cheap in .net. They build on structured exception handling and that is expensive. So short of rewriting the .net runtime I can't think of anything to make exception handling cheap. Possibly it's a bit faster on 64 bit systems since SEH works differently there.
The correct solution is to refactor the APIs that throw the exceptions to not throw so often. For example by returning status codes. If they are third party code you can't change, then I have no idea how to improve your performance.
Or you could write code similar to the one that throws the exception that detects the error conditions beforehand. So you don't call the API anymore if you know it will throw. While this violates DRY, with third party code this might still be the only viable solution.
精彩评论