0

I have quite a large class that uses many more classes. It uses external resources (database, files etc.) and a few exceptions might happen.

As I learned, sometimes it is preferable to use the event of UnhandledException instead of putting try-catch blocks everywhere.

However, my class is just one of many other classes and the aforementioned solutions work at the application-level.

Can I somehow narrow it down to get fired only if the exception fired in this class and the other unhandled exceptions don't get caught?

Using AOP seems like a good way but I'm not sure.

Nestor
  • 8,194
  • 7
  • 77
  • 156
  • 1
    If you handle an exception in a "class" then it is not an unhandled exception. Only ever add try/catch when you *know* how to handle it *and* can meaningfully continue running the program. Both conditions are rarely true. – Hans Passant May 29 '15 at 10:06

1 Answers1

1

I'm not sure if I entirely understand your question, but allow me to try to answer it anyway: You're asking if it's possible to load your class in such a way that it knows which of the exceptions it might generate, are being handled in the class that's loading the dll? This seems impossible, simply because of the calling hierarchy. What I would suggest is that you document which exceptions may be thrown in your classes, using this mechanism:

/// <exception cref="ArgumentOutOfRangeException">Thrown if argument is greater than the size of the array.</exception>

That way your calling classes can be better prepared to handle the exceptions, and know more or less which possible exceptions aren't being handled.

Another approach is to encapsulate your code in try-catch blocks, and use the fact the more specific exceptions are handled first. You can then handle the scenarios you can resolve programmatically, and then catch the generic Exception last to ensure your program remains stable even if underlying classes fail catastrophically.

Unfortunately I don't see how you're going to tell your called dll, which of the exceptions it might throw are being handled.

  • Thanks for the explanation. I intend to avoid try-catch block as they cause performance degradation but based on your opinion, I eventually must make use of them. I will look into AOP, perhaps they offer some customizable approach. – Nestor May 29 '15 at 09:13
  • 1
    @Nestor Try-catch blocks do not cause performance degradation (see here: http://stackoverflow.com/a/3480151/261050), only thrown exceptions cause degradation. So minimize the amount of exceptions you throw, and you'll be fine. – Maarten May 29 '15 at 13:21
  • @Maarten Thanks, for pointing it out, I'll consider this, too. – Nestor May 29 '15 at 13:29