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.

  1. Trace initialization

    Explain what constructor establishes.

  2. Release resources

    Use an explicit cleanup path after work.

  3. Distinguish lifetimes

    Separate memory reclamation from timely resource release.

A resource has an explicit use interval

  1. Construct

    Initialize the usable session state.

    open = true
  2. Use

    Perform the report operation.

    try
  3. Cleanup

    Release the session on the exit path.

    finally → close
Read these stages alongside the complete example. They explain the relationship; they do not execute code.

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
false

A 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
false

Apply 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

false

Recognize 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

Why place close in finally?
Choose one answer. You can try again.

Answer and explanation

It supplies a cleanup path after ordinary success or exception unwinding.

Yes. Cleanup should not depend only on success.

Apply the idea to a new situation

Does JavaScript garbage collection guarantee prompt file closure?
Choose one answer. You can try again.

Answer and explanation

No; use the API’s explicit or structured resource-management pattern.

Yes. Resource release needs its own contract.

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.

    Next lesson: Instance Members and Static Class Members →