try-with-resources

Lab Java Advanced 30 points

Create a class Resource implements AutoCloseable that prints open NAME when created and close NAME in close(). Read names; for each, use it in a try-with-resources block that prints use NAME and throws IllegalStateException if the name is bad. Catch it and print caught.

Input

n, then n names.

Output

The trace of events.

Example

Input

2
file
bad

Output

open file
use file
close file
open bad
use bad
close bad
caught
Sample input available Sample output available
Editor
Java

Hints

try (Resource r = ...) { } closes r automatically.

close() runs before the catch block.

Solution explanation

try-with-resources guarantees close() - this is how files, sockets and database connections are handled safely.

Show solution
import java.util.Scanner;

class Resource implements AutoCloseable {
    final String name;

    Resource(String name) {
        this.name = name;
        System.out.println("open " + name);
    }

    void use() {
        System.out.println("use " + name);
        if (name.equals("bad")) {
            throw new IllegalStateException("bad resource");
        }
    }

    @Override
    public void close() {
        System.out.println("close " + name);
    }
}

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        for (int i = 0; i < n; i++) {
            try (Resource r = new Resource(sc.next())) {
                r.use();
            } catch (IllegalStateException e) {
                System.out.println("caught");
            }
        }
    }
}
Output
Answer
HOME LEARN COMMUNITY DASHBOARD