One of the long-running debates here has been the use of exceptions for managing workflow. This was especially fierce while we were working on the Javascript framework, but it has died down a little in the strongly-typed .NET world.

The two major questions are:

... when should should you return false / null and when should you throw an exception?

I've always been of the opinion that a method should only throw exceptions for events that are truly fatal. For example, a search method returning no results is not an exception. However, a method that internally uses that search method may throw an exception under certain scenarios if it was intending on operating those results.

Others are of the opinion that everything should be thrown as an exception. The argument is that even something like no results should trigger exception-handling code, and the easiest way to do this is have the callee fall into a catch block.  ( I would counter that, even in the catch block, you need to special case different scenarios, so why "pretend" that something is an exception? To me, it seems clearer what's going on )

... should the framework ever handle an exception itself, or always throw to the callee?

Generally, anytime something is truly an exception, I think it should be re-thrown. However, there are cases based on how the code may be called that necessitate handling the exception.  One scenario we dealt with in terms of our Javascript framework was with asynchronous callbacks. If an exception occurs, there is no application code to rethrow it into, so we must either handle it ourselves or get an ugly "exception thrown and not handled" dialog.

It helps if you can dynamically determine whether there is an appropriate callee, which we are able to do in .NET and potentially in Javascript as well.

So... What's your best practice / opinion?


blog comments powered by Disqus