I need some advice with exceptions.
Good .net code requires many skills.
There's a few skills I consider mandatory when it comes to writing good .net code.
- An understanding of the language.
- An understanding of the platform.
- An ability to think logically and to get your ideas out succinctly.
- An ability to think outside the box to find those tough solutions.
- An ability to research, to find out what you need to know when you don't know it.
There's many many more of course.
And here's one. Exception handling skills. Good exception handling involves a few different things, not the least of which is handling it. But I've come across something that I really can't decide on. I can see good points and bad points.
Should exceptions be thrown across boundaries?
I mean real boundaries. A web service boundary.
If I call a web method and an exception occurs on the remote server, should I expect an exception back?
Sure, there's times when they're unavoidable. There's a whole range of HTTP exceptions that could be thrown that aren't thrown by the web method author. But what about when it's a direct result of code within the web method?
Some examples:
- Web method requires a valid parameter, but receives null. Normally, that's an ArgumentNullException. Normally you'd return that up to the caller.
- Database was down. That's a SqlException. Normally you'd try and recover from that - but as a result have no data to return.
- I'm a silly coder who threw a NullReferenceException because I didn't know to check if something that might have problems actually returned what I was expecting.
But calling a web method is not the same as calling a normal method. Should I throw an exception across the web service boundary? Should I craft my messages such that there's no actual exception thrown, but I can show in the message that it failed, and leave it at that? Is returning null when I was supposed to return some object a good enough sign that something went wrong?
I really don't know.
In my class libraries I've always been of the opinion that while I an throw exceptions if I have to (but try not to) I shouldn't let any escape from under my grasp unless I really have to. My catch clauses make sure that I can keep on running normally, maybe just returning null instead of a valid object, maybe trying again a different way (database might have been temporarily down, say, or credentials are needed for a web call).
But this is different. It feels different. It feels like I should be doing different. A lot of googling hasn't really led me anywhere - there's a lot about how if you throw an exception from within a web method you should take care not to expose sensitive information to the caller, but I can't find a recommendation either way about whether you should throw it in the first place.
Talk to me guys :)