Question

I'm currently make a Helper class that can be used by multiple team members. Helper class uses third party API. And I have a question about that handles exceptions in the Helper class.

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/exceptions/creating-and-throwing-exceptions

Looking at the link above, there is a subject like this:

Don't throw System.Exception, System.SystemException, System.NullReferenceException, or System.IndexOutOfRangeException intentionally from your own source code.

Don't create exceptions that can be thrown in debug mode but not release mode. To identify run-time errors during the development phase, use Debug Assert instead.

My question is:

  1. If System.NullReferenceException or System.IndexOutOfRangeException is thrown in the method of Helper class, how should I handle it? Do nothing, and let the exception be propagated automatically? Or do I get the exception, add some information and rethrow it?

  2. How do I handle the exception thrown by third party api? In this case too, should I get the exception, add the information, and then rethrow it?

  3. It is told to use Debug Assert to identify runtime errors in release mode. Does this not apply to the Helper class?

Was it helpful?

Solution

I suggest that your "helper" class should be prepared to catch any exceptions that you expect it to throw. It should then, if necessary, throw an your-application specific exception that corresponds to it.

And then – if the third-party class throws an exception that you didn't anticipate, catch that one also. Gather information from it and then use that to throw an also-application-specific "we just hit an iceberg!" exception.

Either way, your "helper" is responsible for absorbing "whatever happens," and turning it into something that the rest of your application knows how to deal with.

It is very beneficial to structure your "application-specific exceptions" into a class hierarchy.

OTHER TIPS

That advice is only talking about what follows throw new in code you have written. It is not saying anything about how to deal with those exceptions. It does not answer your question 1. or 2.

It is told to use Debug Assert to identify runtime errors in release mode.

No, it told you to distinguish debug error handling from release error handling by using Debug Assert, not by conditionally throwing exceptions.

I think it's perfectly fine to throw system.exceptions. Though you should never expose messages from these outside your application because they can contain sensitive information. I usually create a error handler and have special rules setup and the default rule is Message = "Internal server error". Than I have rules for Argument exception, authentication exception etc

Licensed under: CC-BY-SA with attribution
scroll top