-2

I'm creating a function and want it to be able to give meaningful error message whenever it encounter an error.

I would like to ask whether this situation is a proper use of custom exception, and if not what is appropriate way to handle it.

Example :

int res = a - b;

if (res < 0)
throw new MyCustomeExp("Invalid input. 'a' should be larger than 'b'.");

Does using custom exception for such purpose is proper ?

Thank you.

nvoigt
  • 75,013
  • 26
  • 93
  • 142
hollycrab
  • 315
  • 3
  • 13
  • 1
    This is a rather opinion-based question. My opinion is to just use an `ArgumentException` – ryanyuyu Jun 08 '15 at 14:36
  • Using custom exceptions makes sense if you plan to catch them elsewhere by their type. Otherwise you can just use Exception class or one of the standard exceptions defined in the System namespace – Denis Yarkovoy Jun 08 '15 at 14:37
  • use the exceptions that .net gives you first, then write custom ones. – Daniel A. White Jun 08 '15 at 14:37
  • You should ask yourself if the benefit of having custom exceptions justifies their costs. – Tim Schmelter Jun 08 '15 at 14:38
  • @TimSchmelter Where does creating a custom exception cost more then just creating an instance of any existing one? – MakePeaceGreatAgain Jun 08 '15 at 14:41
  • 1
    @HimBromBeere: it costs development time and you need to maintain/test it. It also creates dependencies if the solution consists of multiple dll's and you want to use the exception-types across different projects or handle them in a different layer than where they were raised. – Tim Schmelter Jun 08 '15 at 14:42

2 Answers2

0

You could also use Trace.Assert():

int a = 42
int b = 56
Trace.Assert ( a > b );
...
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
mikeb
  • 10,578
  • 7
  • 62
  • 120
  • 1
    `Trace.Assert` does not get removed in a release build. `Debug.Assert` does. Check out the page I linked to, it has the explanation. – mikeb Jun 08 '15 at 14:43
0

You should use custom exceptions in very few cases.

Your first filter should be "Am I going to catch (MyCustomExc x) anywhere at all?" If the answer is "no" you don't need a custom one. The answer may be a bit trickier depending on how you log things, your catch may not be a catch at all but a trigger somewhere else outside of your app (ex: send an email when some exception is logged)

Second filter is to check there are no suitable and more generic. If there's a standard one - use it.

Third filter - do you really need an exception or is should something be returned to the caller.

If you still want a custom exception then consider what should it inherit and make sure to only and always use your custom exception for the cases it was meant for - don't go back and forth with generic exceptions.

Sten Petrov
  • 10,943
  • 1
  • 41
  • 61