Software Lesson learned today: only catch exceptions you expect.
Let’s say you have a method called UserFind(userid) that looks for a user and throws an exception if not found. Don’t do this:
Try
{
User x = UserFind(userid)
}
catch
{
showError(“User not found”);
}
If something funny happens, like your database changes a column name, then you’ll never know what happened—it’ll just say user not found.
While it’s more work, you really need to create a DataNotFoundException and throw that in the UserFind.
And make it like this:
Try
{
User x = UserFind(userid)
}
catch (DataNotFoundException)
{
showError(“User not found”)
}
This way if you change a column name, you’re catching a DataNotFoundException. But if you get a SqlException, you will let it pass and crash the application.
“OMG, I don’t want my application to crash!” Well, of course you don’t. However, if someone changed a column name, you’ll find out about it a and find out the cause lot quicker in testing this way. Besides, your application shouldn’t crash anyway, it should just be crippled for that part of your program. And it already was anyway, you were just hiding the fact.
I really already knew the “correct” way to do exceptions was to make small grained exceptions and filter this way. But it just seemed like so much extra typing that I typically didn’t do it. And really I would like it if I could declare the constructor that takes a string for the exception with less boilerplate repetitive code… Ruby style metaprogramming would be great for this. I’d just say something like “declare_exception DataNotFoundException, DataException”. But then Ruby’s deal with not automatically calling the base class constructors really ticks me off…
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment