It doesn't happen often, but I sometimes come across cases where I miss Java's checked exceptions, especially in medium sized methods of about 30 odd lines that call outward. Often, the following pattern emerges:
bool Foo(){
LibType l1 = new LibType("bla");
LibType2 smt = l1.bar("context");
...
...
}
and I want to know when which part of the function has thrown an exception. I know that the external library Lib exposes LibException, and that l1.bar should throw that in some case. But I have no language level guarantees. What I would like is
bool Foo(){
try {
LibType l1 = new LibType("bla");
LibType2 smt = l1.bar("context");
...
...
...
return true;
} catch (LibException le){
//take appropriate action by flogging the library
//log that the exception has occurred in Lib while trying to Foo.
return false;
}
}
but I can't be sure there will not be any other exceptions. In fact, this doesn't even compile, as not all code paths return a value, so I will have to catch a more generic Exception, which could have come from any part off the method.
What I have done, is create a wrapper function, to ensure that all exceptions will be LibExceptions:
private T Wrapped<T, E>(Func<Exception, E> buildException, Func<T> f) where E : Exception {
try { return f(); }
catch (E) {
throw;
}
catch (Exception ee) {
throw (buildException(ee));
}
}
so I can now be ensured a block can only throw the wrapping exception by wrapping it like so
bool Foo(){
try {
LibType2 smt = Wrapped(e => new LibException(String.Format("Unexpected exception: {0}", e.Message)), () => {
LibType l1 = new LibType("bla");
return l1.bar("context");
});
...
...
...
return true;
} catch (LibException le){
//take appropriate action by flogging the library
//log that the exception has occurred in Lib while trying to Foo.
return false;
}
}
I see smells aplenty though, and I am bending stuff in ways I get the feeling it wasn't designed to bend. Is this basically OK? are there things to be on the lookout for? Or is this one off those stop trying to be clever, and slowly back away from the computer
moments?