was successfully added to your cart.

Handling Exceptions in C# – Video and Resources

How to Handle Exceptions Correctly

Handling exceptions is about more than just putting try catch blocks in your code. Where you put them is very important. It is also important to know when not to put a try catch in your code.

This video covers the best practices of exception handling as well as how to rethrow exceptions, create new exceptions, and capture specific exceptions.

Project file download: HandlingExceptionsDemo

Join the discussion 2 Comments

  • Louise Eggleton says:

    As usual, great video, but I did want to mention one thing.

    You imply that Exceptions are the right way to inform the user of bad data. Eg Console message for ArgumentException.

    I would rather validate data so that it never gets that far. My validation routines are responsible for messaging with the user.

    I don’t use exceptions for program flow control. If an exception happens it is truly exceptional.

    That allows me to use a global exception handler at the top level with a generic error message to the user and logging for the developer.

    That way my calling code in the UI is not littered with try/catch blocks.

    • Tim Corey says:

      I definitely understand your point and did not want to imply that error handling was a replacement for data validation. However, there are still times you need to have exception handling for bad data. Any time you do not control the entire stack, you should have some recourse for invalid data. For instance, an API has to throw an exception when it gets bad data. It might not look like an exception but that is what it is doing. It is essentially “crashing” the method and saying I can’t go any further. It returns a 400-level error, which is similar to throwing an exception. The same is true if you write a library that someone else might use. For instance, the System.IO.File class has methods that will return exceptions if you don’t give it a valid file path.

      Not knocking your point. I totally agree. Validation needs to be an important part of your application (and at every level).

Leave a Reply