Constructors, Destructors and Resource Cleanup
Create a report session, then release it
A school program uses a report-writing session. It must initialize the session before work and release its resources even if the report fails. Losing the object reference is not a reliable cleanup schedule.
A constructor initializes an instance. Resource cleanup releases things such as handles or connections. Some languages support predictable destruction patterns; JavaScript memory collection does not provide an ordinary class destructor with guaranteed timing.
Trace initialization
Explain what constructor establishes.
Release resources
Use an explicit cleanup path after work.
Distinguish lifetimes
Separate memory reclamation from timely resource release.
A resource has an explicit use interval
Construct
Initialize the usable session state.
open = trueUse
Perform the report operation.
tryCleanup
Release the session on the exit path.
finally → close
Memory lifetime is not an external resource contract
A constructor should establish the valid starting state. Opening files or connections can fail, so initialization and cleanup policies need to match the real API.
Garbage collection concerns unreachable memory and is not a promise to close a file promptly. Explicit close, language resource-management constructs and try/finally patterns address the resource lifetime.
Before starting, review construction and instance methods. These examples use JavaScript; other languages can use different syntax and rules.
Close a simulated session after use
This JavaScript class is a local resource model. It opens no actual file. The constructor sets open to true, and close changes it to false.
finally executes after the try path during ordinary completion or exception unwinding. The final read confirms cleanup. Later file lessons use real APIs.
JavaScript · local teaching example
class ReportSession {
constructor() { this.open = true; }
close() { this.open = false; }
}
const session = new ReportSession();
try {
console.log(session.open);
} finally {
session.close();
}
console.log(session.open);Expected output
true
falseA handled failure still reaches finally
The simulated write throws, catch reports the failure, and finally closes the session. This is why cleanup should not exist only after a success statement.
Abrupt process termination or power loss is outside this simple guarantee. Use the durability and cleanup semantics of the actual resource API.
JavaScript · local teaching example
const session = { open: true, close() { this.open = false; } };
try {
throw new Error('Report failed');
} catch (error) {
console.log(error.message);
} finally {
session.close();
}
console.log(session.open);Expected output
Report failed
falseApply the rule to a small change
Add a closed-state check and call close twice on a simulated session. State what your cleanup contract permits.
Worked answer
This close operation is idempotent: repeating it leaves the same closed state. Real APIs may differ, so document whether repeated cleanup is safe.
JavaScript · local teaching example
class Session {
constructor() { this.open = true; }
close() { this.open = false; }
}
const session = new Session();
session.close();
session.close();
console.log(session.open);Expected output
falseRecognize mistakes and limits
Do not rely on a finalizer or a variable going out of scope for prompt JavaScript file or connection cleanup. Other languages provide different tools, such as Python context managers and C++ RAII.
Avoid throwing or returning a new result from finally unless intentional: it can replace the earlier failure or return and obscure the actual outcome. Cleanup itself can fail and needs a deliberate policy.
For the language or tool rules used here, see JavaScript class behavior.
Check the core idea
Apply the idea to a new situation
Initialize valid state and close deliberately
Construction prepares an instance; cleanup releases resources. Use a documented cleanup pattern for the actual language and API, and keep failure paths visible.
Connect this idea with try/catch/finally and real file operations.
Reaching the recap and completing the quizzes are separate milestones.