Exceptions and memory

When an exception occurs or occurs:

void ThrowException() { try { throw new Exception("Error"); } catch { } } 

is it and how is it removed from memory?

and how does this code differ from the code below regarding deleting an Exception object from memory?

 void ThrowException() { try { throw new Exception("Error"); } catch(Exception e) { } } 
+4
source share
5 answers

The Exception instance simply acts as another object in memory - after the catch method, there are no remaining references to the instance, so it will be deleted on the next line of the garbage collection.

Exceptions are usually not inherited from IDisposable, as there really shouldn't be external resources associated with the Exception. If you do . have an IDisposable exception, you have to look very seriously at the correctness of your architecture and code.

+2
source

The exception is not inherited from IDisposable, so it does not need to be removed. The memory is freed by the GC, as with all .NET objects.

+7
source

The short answer. Don't worry about it, the garbage collector does it.

Long answer. Forget Everything You Know About Memory Management and Read Top 20. Clean Garbage Bins

+2
source

The Exception class will collect garbage when there are no more references to it, and the garbage collector eventually accepts the queue. An exception object is processed like any other object allocated on the heap.

Since the exception object pops up, it will no longer reference it when there are no more methods that catch or throw it above the stack.

Both examples will have the same effect, since none of them throws an exception above, it will exit the link when the method returns.

+1
source

Since Exceptions do not implement IDisposable , they are automatically deleted by the garbage collector, like any other object, if they are no longer referenced, so you do not need to take care of them. Just follow the class example:

 class CustomException : Exception { ~CustomException() { Console.WriteLine("Exception removed"); } } class Program { static void Throw() { throw new CustomException(); } static void Main(string[] args) { try { Throw(); } catch { } } } 
+1
source

All Articles