Search code examples
c#asp.netexceptionuser-defined

When to use a user defined Exception and some good examples/best Practices?


I would assume that most User-defined Exceptions are for Business Logic level exceptions, but what are some good reasons to use a User-Defined Exception and what are some good examples?

Is a user-defined exception's only advantage that you can define a consistent Error Message?

What logic can be written inside exceptions to make them truly more useful?

After all, can't you just do this: throw new Exception("Some Error Message");


Solution

  • Having user-defined exceptions is useful because it allows you to handle different kinds of errors in specific ways. Why does .NET define so many different types of exceptions if they could just throw all exceptions as System.Exception with a different text message? The reason that there are different types of exceptions in .NET is that you can catch individual types of errors and handle them differently. That's the same reason you would define your own user exceptions - so that you can provide a different response based on the type of exception that occurred.

    You can also create user-defined exceptions that include additional data. For example, you could define a severity level based on an enum, an integer error code or anything else that might be useful to the calling program to identify what went wrong. As for logic to include in exceptions, I generally just try to report what went wrong and leave the logic (what to do about the error) to the calling program. In some cases, I have the exception code automatically write the error to a log file if it has exceeded a certain severity level (e.g. warnings are thrown but only critical errors are written to the log file).