Why is the exception a class and not a structure?
- An exception is a single piece of information.
- Exceptions are (or should be) by definition rare cases in the life of an application, so boxing, unpacking and copying is not a problem I guess.
- Exceptions are almost always outside the scope they were thrown from, so there is a risk of having an exception reference stored somewhere, making it a good candidate to advance to the next generation of GC, whereas structures are easier to clean up.
- Immutable Struct is thread safe.
-
You never want the exception to be null (even the compiler or the CLR forces you to do this, try something below):
throw null;
then you get:
NullReferenceException
Is there any specific reason why exceptions are classes?
+3
Creo
source
to share
1 answer
The two most important things are:
- Structures cannot be inherited, so you cannot do any kind of hierarchy in your exceptions
- In case of StackOverflowException, you cannot allocate memory on the stack, you need a heap
+3
MacakM
source
to share