What’s the best way to handle errors? Things won’t always go the way you expect and you’re going to need to plan how to handle errors. Should you use return codes or exceptions? Plus, this episode will help you in other ways. You’ll be glad you listened.
This episode explores this question with five different ways to handle errors. The error handling strategies are first described with a real life example and then again as they relate to programming. You learn how to:
- Ignore the error. While it might seem like you’re writing resilient code because you can recover on your own, this is really not a good choice.
- Hide the error. This is even worse than ignoring an error. You’ll have enough bugs already and don’t need to purposefully add more.
- Return an error code. Sometimes this really is the right approach. It’s simple and direct. The only problem is that the caller can decide to ignore the return value.
- Throw an exception. This is my preferred approach and ensures that the error cannot be silently ignored. Sure, the caller can always catch an exception and then decide to do nothing about it. But there’s only so much a single method can do.
- Make an assertion. This allows your method to verify anything it wants and to stop the entire program if anything doesn’t look right.