Proper use of custom exceptions

107 views Asked by At

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.

2

There are 2 answers

0
Sten Petrov On BEST ANSWER

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.

1
mikeb On

You could also use Trace.Assert():

int a = 42
int b = 56
Trace.Assert ( a > b );
...