1

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 trying costs nothing, but catching 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.

xtofl
  • 40,723
  • 12
  • 105
  • 192
  • 1
    Extremely curious to see what the community responds with, as this kind of message-handling is stupidly common. =) – J. Steen Jun 16 '11 at 10:36
  • What kind of api is it? For example, is it a web site, or is the source code available so you can predict the outcome so you don't even need to call the api? – agent-j Jun 16 '11 at 10:39
  • @agent-j: It's a COM class, returning a `HRESULT` error code, which is translated into an Exception in .NET – xtofl Jun 16 '11 at 10:57
  • I'm not too familiar with COM interop, but it should be possible to prevent the mapping to an exception. – CodesInChaos Jun 16 '11 at 11:39
  • @CodeInChaos: indeed. Cfr. http://stackoverflow.com/questions/6371117/com-hresult-is-wrapped-into-an-exception-in-net/6371302#6371302 – xtofl Jun 16 '11 at 11:56

1 Answers1

2

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.

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262