I have this class :
public class TempFileRef
{
public readonly string FilePath;
public TempFileRef(string filePath)
{
FilePath = filePath;
}
~TempFileRef()
{
File.Delete(FilePath); //<== what happens if exception ?
}
}
Question :
What happens if there is an Exception in the destructor ?
1) will it break the other finalization's in the F-Queue ?
2) I i'll wrap it with Try
and Cache
- I will NEVER
know that there was an error
3) what
should I do here ?
The MSDN pattern for it based on "if I **forget** to call the Dispose method - so the GC will do it eventually.... it is better later then never..."
. So my question is specially about exception in the Finilize ( destructor)
The C++ rule is that you must never throw an exception from a destructor that is being called during the "stack unwinding" process of another exception. For example, if someone says throw Foo(), the stack will be unwound so all the stack frames between the throw Foo() and the } catch (Foo e) { will get popped.
9. How to handle error in the destructor? Explanation: It will not throw an exception from the destructor but it will the process by using terminate() function. 10.
Most people say never throw an exception out of a destructor - doing so results in undefined behavior. Stroustrup makes the point that "the vector destructor explicitly invokes the destructor for every element. This implies that if an element destructor throws, the vector destruction fails...
The short answer to the question “can a constructor throw an exception in Java” is yes!
This actually depends on the .NET framework
For example in .NET 2 and .NET 4, you application will be terminated
If Finalize or an override of Finalize throws an exception, and the runtime is not hosted by an application that overrides the default policy, the runtime terminates the process and no active try-finally blocks or finalizers are executed. This behavior ensures process integrity if the finalizer cannot free or destroy resources.
In contrast in .NET 1, only that finalizer will be terminated and your application will continue running:
If Finalize or an override of Finalize throws an exception, the runtime ignores the exception, terminates that Finalize method, and continues the finalization process.
What you actually trying to do is to implement an IDisposable
pattern, so instead leaving this work to a finilazer, do it in the progrmatically called Dispose
.
From MSDN :
Exceptions that occur during destructor execution are worth special mention. If an exception occurs during destructor execution, and that exception is not caught, then the execution of that destructor is terminated and the destructor of the base class (if any) is called. If there is no base class (as in the case of the object type) or if there is no base class destructor, then the exception is discarded.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With