.NET exception advice:
Q: What should I throw?
A: System.Exception
Q: What should I catch?
A: System.Exception
The .NET exception model is a Pokémon based system. Gotta catch them all.
Q: What should I throw?
A: System.Exception
Q: What should I catch?
A: System.Exception
The .NET exception model is a Pokémon based system. Gotta catch them all.
Determining all the exception types a given API can throw is often not a realistic exercise:
- Has a delegate? Repeat the exercise for all methods / lambdas used for that type
- Has an interface? Repeat the exercise for all implementations
- Has a delegate? Repeat the exercise for all methods / lambdas used for that type
- Has an interface? Repeat the exercise for all implementations
- Has a non-sealed method invocation? Repeat exercise for all overrides.
- Has COM? track down all Marshal.GetExceptionForHR
- Has IO / PInvoke or really any win32 call? Can throw pretty much anything depending on how error codes are handled.
- Has COM? track down all Marshal.GetExceptionForHR
- Has IO / PInvoke or really any win32 call? Can throw pretty much anything depending on how error codes are handled.
Often this leads to cases where you simply can't track down all the exceptions. Particularly once interfaces or delegates are involved because you can't track down all of the implementations. That's a reality you have to accept.
That's why catching Exception is the most pragmatic approach. If you believe that an API can recover from an exception then just catch Exception and handle that.
The cases for catching more specific exception types is fairly narrow. Pretty much when you want to react to a specific type of failure like OperationCancelledException.
Most times though you just want to handle that an API failed, not specifically why it failed.
For example: don't handle FileNotFoundException when reading from a file. IO can fail in so many different ways. How the IO failed is really not that interesting, what is interesting is that it failed. So just handle Exception.