Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining exceptions that can be thrown from a toolkit API

Is there a best-practice or industry standard for throwing exceptions from a toolkit API?

Should the user facing methods catch and wrap up Exception in some sort of CustomException so that users only have to worry about CustomExceptions coming out of the API?

Or is the convention to just let those bubble up?

We're concerned with being able to document all possible exceptions our API methods might throw. (For example, if our API method calls Stream.Write() which throws 4 or 5 exceptions, we'd have to document all of those in addition to other exceptions that other called methods might throw.)

We were thinking of doing something like this:

public void customerFacingApiMethod(){
   try {
      //api functionality goes here
   } catch (Exception e) {
      throw new CustomException(e);
   }
}
like image 870
Ovi Tisler Avatar asked Dec 03 '09 21:12

Ovi Tisler


3 Answers

In my opinion having the API throwing only one exception type is a bad idea. One of the good things with different exceptions is that you can choose to catch different types of exceptions and handle them differently. Wrapping up exceptions into a single exception type would remove that facility.

Use the exception types provided by the framework where appropriate, and create your own custom exception types for specific situations where appropriate. And above all, make sure to document for each method which exceptions they may throw.

like image 106
Fredrik Mörk Avatar answered Oct 21 '22 10:10

Fredrik Mörk


When throwing exceptions, make sure that the user-facing exceptions are all relevant to what the user actually did wrong with regards to your toolkit. That might mean catching or merging different filesystem exceptions into a single exception but you shouldn't ever just catch Exception and throw a new one - that's not actually telling the toolkit user what they did wrong.

like image 3
Alex Kaminoff Avatar answered Oct 21 '22 09:10

Alex Kaminoff


You should follow the same concepts as the .NET Framework. Your users already use the framework, so they know how it works and expect certain behavior.

  • Throw an ArgumentException-derived exception if an argument from the client is invalid (use ArgumentNullException, ArgumentOutOfRangeException, etc. as appropriate).
  • Throw an IOException-derived exception for IO errors.

Etc...

In your documentation, clearly state the preconditions for your public API and state the exceptions that will be thrown when they fail (like MSDN does).

like image 3
Sam Harwell Avatar answered Oct 21 '22 09:10

Sam Harwell