Create Custom Exceptions

custom exceptions

 

It took me years to get my head around how to use exceptions. The mechanics of throwing and catching exceptions is simple enough to grasp. 

After that, you’re on your own—there is not much information on how to use exceptions. When and why would you throw exceptions? How do I set up my system to handle exceptions gracefully? Is there a pattern for exceptions? 

Yes, there is, and in this series on exceptions, I will show you how to use them properly.

Last time we got started with why we should avoid throwing raw exceptions:

  throw new Exception("This customer already exists.");

If we are not supposed to throw plain exceptions, then what should we do instead?

We should be creating Custom Exceptions.

For example, instead of throwing the above raw exception, we could design a custom exception:

 

  public class DuplicateCustomer : System.Exception
  {
     public DuplicateCustomer() : base("This customer already exists.")
     { }
  }

And here is how we throw it

  throw new DuplicateCustomer();

This approach is not perfect—not yet—but it’s an improvement:

  • We have encapsulated the error message “This customer already exists.” into the custom exception type. In this way, we get consistent error messages when reusing the exception.
  • We can catch and handle this exception by type, as in catch(DuplicateCustomer). As we discovered last time, catching plain exceptions is tricky; we can only identify them by their exception message—a fragile strategy.

So, please consider creating and throwing custom exceptions. 

In my next article on exceptions, we’ll delve into the rules I like to use to name exceptions.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply