019-007-008

Resource Cleanup on Exception

Medium

Problem Description

Resource Cleanup on Exception

Learning Objective: Understand that resources are reliably released even when exceptions occur in try-with-resources

Overview

Create a DatabaseConnection class and verify resource is closed even when exception occurs during processing.

Specifications

  • DatabaseConnection class: implements AutoCloseable
    • connect(): outputs "Connected to database"
    • executeQuery(boolean shouldFail): throws exception if shouldFail is true, outputs "Query executed" if false
    • close(): outputs "Connection closed"
  • In main, test behavior on exception

Output Format

Connected to database
Connection closed
Error: Query failed

Ready to Try Running Code?

Log in to access the code editor and execute your solutions for this problem.

Don't have an account?