I am talking based on experience with Java and C#. I do not know if other language have different exception handling implementation.
In order to achieve loose coupling, we need our code being programmed to use abstraction rather than implementation. However the exception handling case is the opposite. The best practice is you need to handle specific exception type (SqlException
, StackOverflowException
, etc).
This thing may be better (or not) in java thanks for it's Checked Exception
, there is a kind of "contract" between the interface and the consumer. But in C# or for the Unchecked Exception
there is no contract about what exception can be thrown by the interface.
For example, say that we use Repository Pattern
to decouple the DAL with BLL. The simple catch exception usually be used like:
public void Consume()
{
try{
productRepository.Get(k=>k.Id == "0001");
}
catch(Exception e){
// handle
}
}
In more specific case we usually use SqlException
. However it means that we must know that the ProductRepository
is a repository to database server. What if the implementation changed to use file repository instead? Now you need to catch FileNotFoundException
or something like that.
Why does it violates the "code to abstraction" principle? And what can we do to prevent it?
strenghthen the precondition
. Taking assumption that interface itself will not throwing any exception other thanNullReferenceException
.