Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exceptions and memory

When an exception is thrown or encountered:

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

is it & how is it disposed from memory?

and how does the above code differ from the below code in respect of the disposal from memory of the Exception object?

void ThrowException()
{
    try
    {
        throw new Exception("Error");
    }
    catch(Exception e)
    {
    }
}
like image 646
divinci Avatar asked Dec 14 '22 04:12

divinci


2 Answers

Exception does not inherit from IDisposable so it does not need to be disposed. Memory deallocation is done by the GC like for all .NET objects.

like image 53
mmmmmmmm Avatar answered Dec 31 '22 14:12

mmmmmmmm


The Exception instance simply acts as another object in memory - after the catch method, there aren't any remaining references to the instance, so it will get removed in the next garbage collection sweep.

Exceptions generally don't inherit from IDisposable, as there shouldn't really be external resources associated with an Exception. If you do. have an IDisposable exception, you should look really hard at whether your architecture & code design is correct.

like image 29
thecoop Avatar answered Dec 31 '22 15:12

thecoop