Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what happens when an unhandled exception is thrown from a constructor

What happens when an unhandled exception is thrown from a constructor? For Java, and for C++? Will there be a memory leak?

like image 935
dacongy Avatar asked Dec 21 '12 01:12

dacongy


1 Answers

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 function std::terminate() is called; whether or not the stack is unwound before this call to std::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 no catch clause that can handle an exception can be found, then the current thread (the thread that encountered the exception) is terminated. Before termination, all finally 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.

like image 160
Cheers and hth. - Alf Avatar answered Sep 30 '22 00:09

Cheers and hth. - Alf