What happens when an unhandled exception is thrown from a constructor? For Java, and for C++? Will there be a memory leak?
You ask,
“What happens when an unhandled exception is thrown from a constructor? For Java, and for C++? Will there be a memory leak?”
An unhandled exception is an exception that does not have an associated handler.
In C++ any unhandled exception terminates the program. It is unspecified whether the stack is unwound in this case, i.e. destructors of successfully constructed local variables may be executed or not depending on the compiler. Where the exception is throw from (such as inside a constructor) is irrelevant.
C++11 §15.3/9:
“If no matching handler is found, the functionstd::terminate()
is called; whether or not the stack is unwound before this call tostd::terminate()
is implementation-defined.”
An unhandled exception in Java likewise necessarily terminates the program, or at least the current thread if it’s not the main thread, but with guaranteed calls of finally
clauses:
Java SE 7 Language Specification §11.3:
“If nocatch
clause that can handle an exception can be found, then the current thread (the thread that encountered the exception) is terminated. Before termination, allfinally
clauses are executed […]”
Since the program terminates there is in practice no memory leak for the program itself, because in practice the operating system cleans up after a process.
However, a crashing program may leave temporary files on disk, and it may leak other resources from server processes, including memory leaks in those server processes.
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