From the course: Java SE 21 Developer (1Z0-830) Cert Prep

Unlock this course with a free trial

Join today to access over 25,500 courses taught by industry experts.

Implementing AutoCloseable, part 2

Implementing AutoCloseable, part 2 - Java Tutorial

From the course: Java SE 21 Developer (1Z0-830) Cert Prep

Implementing AutoCloseable, part 2

- As we've mentioned, the close method can throw an exception. Ours is declared as doing so but doesn't actually do it yet. But even if it does throw an exception, it will not affect the attempt to close other resources. Let's take a look at that. We'll modify our closing method. We're gonna put this code in here so you'll notice, randomly, 50% chance, we decide to fail the closure. We'll print a message when we do, and we'll throw an exception, the SQLException, even though it has nothing to do with databases, to say that Closing failed to the caller. So we should get a message to that effect and an exception. And if we don't actually do that, then we will print another message that says our closure was successful. In this case, you can see we initialize our three resources. We use our three resources in the try block. Then we call Closing for id 2 and it fails. We call Closing for id zero and it fails. We call Closing…

Contents