Exceptions. Nobody likes when they occur. Yet everyone throws them left, right, and center. Heck, even .NET throws an exception every time you use a particular type incorrectly. In this email, I’ll review tips, tricks, and best practices when working with exceptions. Some of them are common sense. Some are neat C# features and recent additions to the .NET ecosystem. And some are ways to save yourself from bugs caused by exceptions. Let me show you how to write exceptionally great code. Where exceptions are used, but not abused. 1. Prefer throwing a specific exceptionThe easiest way to throw an exception is to throw a generic Exception type. But that’s like telling the doctor: “I’m in pain. Give me a solution.” Instead, when you need to throw an exception, throw a more specific one, for example, ArgumentNullException. Or create a custom exception. Like InvalidUserInputException or OrderNotFoundException. Your future self will thank you when debugging. 2. Internalise messages in custom exceptionsWhen you create a custom exception, encapsulate the error message inside it: This ensures that changes to the message format are made in one place. Rather than scattered across your codebase. 3. ThrowIf methodsA simple way to add a guard clause to the start of your method is to use ThrowIf* family of static methods: Some key .NET exception types have static throw helper methods that allocate and throw the exception. Here is the list: 4. Throw vs throw exWhen rethrowing an exception, don't use throw ex. It wipes out the stack trace and makes debugging a nightmare. Instead, use throw to preserve the original context. 5. Use catch when expressionHave you ever wanted to handle exceptions only when certain conditions are met? Starting with C# 6, you can use catch when expression: But you can also use it to handle different types of exceptions with one catch block: 6. Consider using Result for execution flowRather than relying on exceptions for control flow, you can use the Result pattern to return success or failure without triggering an exception. This approach is cleaner and avoids the performance hit of throwing exceptions unnecessarily. This can get a bit messy when you need to propagate and check for result status within different layers of code. .NET team is considering adding discriminated unions inside .NET in future versions to support Result type natively. 7. Don't ignore exceptionsAll exceptions should be appropriately logged and handled. With .NET 8, you can easily centralize your exception handling with a global error handler. This ensures consistent logging and error responses across your application, reducing duplication and improving maintainability. Once you implement and register it, you can simply call app.UseExceptionHandler(); to enable it globally. Centralize the chaos, simplify the solution. 8. Use finally to release resourcesTo minimize memory leaks and performance issues while using external resources in your code, such as:
You need to release them after you are done. There are two ways to do it:
9. Handle common conditions to avoid exceptionsNot every problem requires an exception. Handle common conditions proactively to avoid triggering unnecessary exceptions. For example: Prevention is better than cure. 10. Call Try* methods to avoid exceptionsC# provides many Try* methods that allow you to avoid exceptions by returning a success/failure boolean. Use these when appropriate to keep your code efficient and clean.
I’m not a doctor. Or can offer financial advice. But if you follow the 10 golden rules above, managing exceptions will be easier. Enjoy your weekend.
|
Weekly newsletter packed with code-improving tips, tools, and strategies to become a better .NET developer.
Lately, I’ve been paying more attention to what’s happening in the AI space. Maybe because of all the hype that surrounds it. Maybe because of the anxiety of whether AI will take my software development job. That's why I’ve decided to spend some spare time during the Xmas holiday to explore the state of AI software development tools. This email combines: My 1+ years of experience using a paid version of GitHub Copilot. 5+ hours of YouTube videos I’ve consumed in the last 2 weeks. So, let’s...
Today's issue is brought to you by the C# 13 and .NET 9 – Modern Cross-Platform Development Fundamentals. Build confidence in creating professional and high-performance web applications using the latest technologies in C# 13 and .NET 9 by Mark Price. Find out more here: C# 13 and .NET 9 Yesterday, We had a company Xmas party. Before dinner at a restaurant, we went to the escape room event. If you are unfamiliar with escape rooms, they're interactive puzzle experiences where you and your...
2 weeks ago, .NET 9 was released. If you haven’t had time to read the official release docs, don’t worry. I spent 1 hour investigating what's new in .NET 9. So you don't have to. Here are the top 10 improvements for C#, ASP.NET Core, and EF Core. 1. LINQ Index LINQ has always been an extremely useful tool for .NET developers. However, with .NET 9, LINQ comes with 3 new methods. Let's begin with the LINQ Index. The Index method places every collection element against its position within that...