Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throwing exceptions for legal states in code

Tags:

c#

.net

exception

The Exception is a convenient container, that is tempting to use for various purposes. But is it OK to use it for handling legal states in your code?

My example: I have a geometric function that finds the closest object within a search radius:

public IPoint FindNearest(IPoint origin, double searchRadius)
{

}

My idea was that I could throw an exception, when the search doesn't find a hit. But is this a good idea? Alternatively, I could return Null (which I don't like), or return a result object instead of a Point.

like image 466
Morten Avatar asked Jan 27 '26 03:01

Morten


1 Answers

Exception, in general, represents an invalid or "exceptional" scenario. In your case, if not finding a hit is an exceptional scenario and it should always be found in usual cases then you can throw exception.

You should always try to avoid throwing exception because of its heavy nature. If caller code is calling this method frequently and your method is in result throwing lot of exceptions, it will make your program slow

like image 172
Haris Hasan Avatar answered Jan 28 '26 17:01

Haris Hasan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!