I like to say that Italy has excellent standards when it comes to laws and rules; the problem is with exceptions. We do have way too many exceptions. And I’m a firm believer that exceptions are excellent as long as they are … exceptional.
A friend skyped this morning that he had met someone in his .NET community who heard me saying back in 2005 that developers should not use exceptions. I’ve read too many crime stories to deny the fact that anything you can say can be used against you. However, I think that what I said in that remote event of about a decade ago was more or less that throwing exceptions should never exceed the level of addressing exceptional situations that might be detected in code.
As I see things, an exception is the net that catches you when you fall down the rope. An exception handling mechanism is more than legitimate to use but is should be the last resort. If there’s a static way to prevent errors and/or anomalies, you should be using that and avoid exceptions. Let’s say that you want to connect to a
web service HTTP endpoint. The action may fail for a number of reasons:
- Lack of connectivity
- The URL is wrong
- The server is not available or times out
The laziest is ignoring all of these possibilities, code straight and wrap the code in a try/catch block. You can check for connectivity beforehand, and gently deny the action if not available at all or too slow (ie, in mobile). And you can pay attention at the HTTP code being returned.
After all of these preliminaries, you may not have protected yourself against all odds. So an exception handler is still useful because you never know. But if you know …