Question

In my C# app I'm throwing custom defined exceptions during the initialization of some very large arrays. How can I release all memory used by the app until an exception is thrown when throwing Exceptions with no catch, so no finally block, but just the throw statement? Or can a finally block be executed after a throw in this context?

Thanks

Was it helpful?

Solution

If you have a local array declaration then you don't need to care about it as it will be collected by GC for you. So if your code looks something like that:

int[] values = new int[100000];

// Some initialization here
throw new ApplicationException();
// Some initialization here

then you don't need to care about it. The same applies to the case if your array variable will go out of scope when the exception will be handled or after that then it will also be GC'ed. The only problem may occur if you have it as a field variable in the class that won't be GC'ed itself (meaning there will be references to it from somewhere else) or static field or similar. If you want to make sure that this will be cleared you can just do like that:

try
{   
   m_Values = new int[100000];

   // Some initialization here
   throw new ApplicationException();
   // Some initialization here
}
catch // use this part if array should be used if there is no exception
{
   m_Values = null;
   throw;
}
finally // use this part if you never need an array afterwards
{
  m_Values = null;
}

So if you use this pattern you can be sure that there will be no references to your array and it will be garbage collected at some point. You can force GC to collect it as well but that's not recommended.

OTHER TIPS

You can use try/finally statements without catch. In this case, finally block will be executed regardless of was exception thrown or not.

try{
    ...
    throw new Exception();
    ...
}
finally{
    //cleanup code
    ...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top