019-005-009
Safe Management of Multiple Resources
Hard
Problem Description
Safe Management of Multiple Resources
In this problem, you will create an executeQuery method that manages two AutoCloseable resources (DatabaseConnection and QueryExecutor) using try-with-resources, returns a result string for valid queries, and throws appropriate exceptions for invalid input.
Learning Objective: Understand how to manage multiple resources with try-with-resources while combining exception handling
Overview
The try-with-resources statement can declare multiple resources separated by semicolons, and they are automatically closed in reverse declaration order. This problem combines resource management with input validation.
Specifications
DatabaseConnection class (implements AutoCloseable)
- Constructor: no arguments
close(): releases the resource
QueryExecutor class (implements AutoCloseable)
- Constructor: no arguments
execute(String query)method:- If
queryisnull, throwsNullPointerException(message:"Query cannot be null") - If
queryis an empty string, throwsIllegalArgumentException(message:"Query cannot be empty") - If valid, returns
"Result: " + query
- If
Main class
- Define
static String executeQuery(String query)method- Declare both
DatabaseConnectionandQueryExecutorin try-with-resources - Return the result of
executor.execute(query)
- Declare both
Examples
executeQuery("SELECT * FROM users")→"Result: SELECT * FROM users"executeQuery(null)→NullPointerException: "Query cannot be null"executeQuery("")→IllegalArgumentException: "Query cannot be empty"
Ready to Try Running Code?
Log in to access the code editor and execute your solutions for this problem.
Don't have an account?
Sign Up