David Tovee asked a great question in yesterday’s Mastering Query Tuning class. He asked his fellow students, “How many of you actually use TRY/CATCH?”
I turned it into a Twitter poll because I wanted to check a wider audience:
When the developers at my company write new queries, they use TRY/CATCH and exception handling:
— Brent Ozar (@BrentO) August 19, 2021
The poll results mirror the experience I see with clients: the vast majority of T-SQL code doesn’t have any error handling whatsoever.
When I do run across error handling in client queries, I get all excited and I ask about it. The answer is usually, “Oh yeah, that was implemented years and years ago by a developer who used to work here, and they left.” It’s often legacy leftovers from when TRY/CATCH was first introduced, and then…never revisited again, and rarely included with new queries.
If you’d like to get started with error handling, check out these resources:
- Error and Transaction Handling in SQL Server – Part 1 – Jumpstart Error Handling by Erland Sommarskog
- Part 2 – Commands and Mechanisms
- Part 3 – Implementation
- SQL Server Error Handling Gotchas by Niels Berglund
Right about here is the part of the blog post where you might expect a finger-wagging lecture from me about how queries should always handle errors, but, uh…I don’t do error handling either. I know, right? But the thing is, I can’t remember the last time a client hired me to write a new query from scratch. If I never do something, then I won’t be good at it, and I certainly can’t lecture you to be good at it, either.
If you DO put error handling into your queries, though, take a moment to hug yourself. You rock, and you’re unusual amongst the wider audience. The world needs more people like you.