Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cost of Custom Exceptions

Tags:

c#

exception

I've read that throwing exceptions is an expensive operation. However, doesn't creating your own exceptions make your code more expressive and readable?

Some of my coworkers suggest that you should just use System.Exception and insert your custom text into the message instead of creating a new custom exception.

I'm interested in other opinions. Appreciate any suggestions.

like image 515
Byron Summerdahl Avatar asked Feb 24 '23 01:02

Byron Summerdahl


2 Answers

Do not throw System.Exception. Ever.

The problem with it resides in the calling code. It is a bad practice to catch the general Exception object for many reasons. If you throw an instance of the Exception base class, then calling code has no choice but to catch Exception if they want to handle it. This forces the calling code to use a bad practice.

Also, the calling code has no reliable means of distinguishing what the exception was, if all it gets is Exception.

It is typically best to use one of the pre-defined exceptions if any are applicable (ArgumentException, InvalidOperationException, etc.). If none correctly describe the situation, then a custom exception class is a perfectly good way to go.

like image 123
Jeffrey L Whitledge Avatar answered Mar 05 '23 11:03

Jeffrey L Whitledge


It's the overhead of throwing an exception itself (creating the object, walking the stack, etc.) that's costly. Making your own exception class adds almost no overhead, so if you're going to throw an exception, don't make it new Exception("message")!

like image 30
Gabe Avatar answered Mar 05 '23 10:03

Gabe