close

Java Try With Resources

the Java try with resources construct

helps you close resources correctly

which have to be closed manually after

use for instance a file or a file input

stream or a network connection like a

database connection in this video I will

explain to you how the Java try with

resources construct works and as you can

see from this screenshot here I also

have a textural version of this tutorial

and I have linked to that tutorial in

the description below this video let's

jump right into the code and see how the

try with resources construct looks and I

have already created an example here to

save a little bit of time as you can see

there's a try block here and after that

we have a parentheses and inside the

parentheses we can declare any resources

that we want to try with resources

construct to handle for us and by handle

I mean automatically close when the try

block exits inside this try block here

inside the parentheses I have created I

have declared a file input stream

variable and I have instantiated a new

file input stream object here and inside

the try block I am reading all the data

from this file input stream and then

when the code exits the the try block

here the try with resources construct

will automatically close the file input

stream for us before Java 9 the

resources that you want to close or you

want extra automatically close by a try

with resources construct had to be

declared inside the air the parentheses

here after the try block but from Java 9

it is actually possible to declare them

outside but you just need to reference

them inside this inside that try with

resources parentheses I will show you

how that works look at this first we

move this variable out here outside of

the try block and then we can just

reference it like this now works but

this only worked from Java 9 and

there's a one restriction on the

resources that you can reference inside

the parentheses of a trial with

resources construct and that is that the

resource must be the variable must be

effectively final which means that this

variable out here must be assigned once

but after assignment it must not be

changed again ahead later on for

instance of you you're not allowed to do

something down here for instance this

new is equal to some other to some other

file as you can see then up here the

compiler complains that this is no

longer effectively final because we are

actually reassigning the file input

stream variable down here but by

removing this reassignment the file

input stream variable actually becomes

effectively final and we are allowed to

reference it inside the tribe with

resources parentheses here part here for

now to keep the examples simple we will

just move their resource declaration

directly inside of the try with

resources block here it makes the code a

little bit simpler the try with

resources construct can handle can

manage can automatically close any

resource or any object that implements

the auto closeable interface and it's

actually possible for us to implement

this interface ourselves in case we have

resources that we want to be able to be

managed by the tribe with resources

construct and I just want to show you

how this looks is actually very simple

so I create a new class here I make it

implement the auto closeable interface

you can see it's in the java.lang folder

it's a it's a coin surface and as you

can see it only has a single method

called close and which can throw an

exception when you attempt to close the

resource if you create a class that

implements this interface you can use it

inside our

the try with resources construct and I

will show you that here right just

actually let's just do it down here

try Auto closable example resource is

equal to and you also close up an

example and you can see now in here we

can use the resource and then once the

execution exits this block here exits

the try block then the try with

resources construct will automatically

call this closed method for us here so

let's try and just I have put in a

little system out here so we can see

this actually works let's just try to

comment out this up here so we don't get

bothered by that let's try to run this

example and see what we get out in the

terminal here look at that

also closeable example closed is printed

out because after this try block here

exits the tribe with resources country

calls our closed method here quite

useful right the try with resources

construct can actually handle more than

one resource for us at a time so let's

just try to see how that looks first of

all I just remove this old example up

here so what we will do here is I will

simply declare another resource in here

which also implements the

the auto closeable interface and as you

can see I'm using the exact same class

and I'm separating the declarations with

a semicolon here with the semicolon so

now they try with resources construct

will handle the closure of both resource

and resource two for us and if we run

this you will see that we will have this

text printed out twice now because we

have two resources that will be closed

for us and that's just as you can see

just like we expected we get the text

printed out twice one little detail to

notice is that when we are letting the

tribe with resources contract handle

multiple resources the order in which

the resources are closed is the reverse

order of which they are declared up here

in the parenthesis that means that when

the resources are closed when the

triblock exits first the resource 2 will

be closed and then resource will be

closed and we cannot see that in the

output down here because the two

instances print out the exact same text

when they are closed but in later

examples the I will show you that this

will become clear because the closed

methods will print out different texts

the exception handling semantics of the

tribal resources were constructed are

slightly different than what you might

be used to from the try catch finally

blocks so we will have a look at that

here and towards the end of this video

to demonstrate the accept exception

handling semantics of the tribe with

resources construct I have created a

special auto closeable resource which

implements the auto closable interface

the auto closeable resource can be

configured to throw an exception either

when you call closed which corresponds

to an exception happening when you close

the resource or you can tell it to throw

an exception when you call due up by

passing true to as parameter to the

method here which corresponds to an

exception happening

when you are using the resource let me

first show you how this works by by

simply going back to the tribe with

resource accessor example here and

replace the auto closable example

resource here with the auto plausible

resource which I just showed you so I

will call this one and I will tell it by

passing force that it should not throw

an exception when we close it and I will

do the same to the second resource here

let's call this a up here resource one

and this we will also turn into a auto

plausible resource and their name will

be

- and I would also tell this one not to

throw any exceptions when you close it

now let me also just show you how to

actually use these resources here I will

call resource one that due up and I will

pass fonts as parameter and I will do

the same to resource - and by passing

phones to the do of methods I'm telling

the resource not to throw an exception

when this method is called

in order to verify that there are no

exceptions thrown from this code I will

just execute it here so you can see the

output down here and you can see first

it's printing out resource one doing

operation which is printed from this

first two up call here and then it's

printing resource to doing operation

which is printed from inside this method

called down here run resource - then you

can see resource - is being closed and

resource one is being closed and as I

have explained earlier the resources

here are closed in the opposite in the

reverse order of which they are declared

here so that means that resource - is

closed first as you can see and then

resource one is closed now let's try to

configure the first resource to throw an

exception when - up is called and we do

that by simply changing the parameter

value here - to true and then let's run

the code again and see what happens

as you can see resource 1 operation is

being called but resource to 2 of is

never called because when an exception

is thrown from this method the code in

the block is of course aborted its

action you know it's M the try block is

exited but as you can see both resource

- and resource 1 are still closed and

you can also see that from the try block

the exception that was thrown in here is

propagated out and it's throwing out to

the to the Java Runtime which then just

prints it out so we can see it here but

as you can see let me just repeat that

that even though the resource here is

throwing an exception when we call it

both resources are being closed

correctly now let's see what happens if

I am also configuring the resource to

throw an exception when it is closed

right so I'd simply change this

parameter to true and I run it again

and as you can see we get the same

behavior as before resource 1 operation

is being called but resource to do up is

not called because an exception is

thrown from this method still that that

breaks the code flow the code execution

of the try block and then when the

execution exits the try block it will

try to close the resources and as you

can see it first tries to close resource

2 which succeeds just fine and then it

tries to call resore to close resource 1

which then fails now now we have two

exceptions being thrown from this try

block so which one will actually be the

one propagated up to the call stack and

the answer is that it is the exception

thrown in here when using the resource

that is propagated out of the try block

even though another exception is thrown

when trying to close to the resource or

one of the resources here and the reason

for that is that most likely the the

exception from using the resource is

more interesting to you it is the root

cause and it and so it's more

interesting to you as a as an

application but also as an as an as

application development that this is the

one you should be looking at handling

and also the exodus exception might be

the one causing also the failure when

trying to close the exception of course

not in this case because this is the

configuration that is causing it but in

in the

in the case of a real resource Winston

that database connection if you try to

call an operation on a database a

connection that has gone stale then that

might throw an exception and then when

you try to close the database connection

that might fail to because this the

database connection is still stale but

when you look at the exception down here

you can see that it has changed because

what has happened is that this exception

thrown from in here is caught by the

Java Runtime and then the exception that

was thrown when trying to close the

resource up here or not up here but like

because I configure it here but from the

close call is attached to the first

resource as what is called a suppressed

exception and we will have a little bit

like a closer look at suppressed

exceptions in just a second

in order to see how these suppress

exceptions work I will add a catch block

to the to the try with resources block

here so this will catch all the

exceptions that are thrown and then

first of all I will just print out the

exception and its stacktrace and then I

will call ethat gets suppressed ether

get suppressed returns an array of

throwables and this is this array will

contain the any suppressed exceptions

that this other exception up here might

contain and now I will print them out

I'll print out the suppressed array and

let's actually try to run this but with

the debugger and see what happens

as you can see an exception was thrown

from in here which causes the code in

the try block to X to exit or to to

break and then we enter the catch block

because an exception was thrown but

before we enter before we enter the

catch block you can see that Java has

already closed or attempted to close our

to resources that means that by the time

we the code enters the catch block the

resources are already closed and as you

can see when we go back into the

debugger because another exception is

thrown I can't figure it to be thrown

when resource 1 is closed you can see

that the array here actually contains

another suppress 3 so our another

suppressed exception and that is the

exception that occurred when Java was

trying to close the resource for us in

case more than one exception is thrown

when trying to close resources then all

of the exceptions that occur when trying

to close resources will be present in

this throwable array here in the

suppressed array and I can demonstrate

that simply by changing the statement or

the the parameters appear to true now

both of the resources will throw an

exception when you try to close it and

then we simply rerun the example in the

debugger now you can see the suppressed

array contains two exceptions because

two exceptions were thrown when trying

to close the resources here ok so now

you should have a pretty good

understanding of how exception handling

works with the try with resources

construct and just just one final thing

that I want to show you let me just stop

this example here and that is what

happens if we have a finally block on

obviously before we even enter the

finally block the

the tribal resources consequent also

have tried to close our resources and

let me just demonstrate how that works

let's first remove the exceptions here

and also remove the exception here so

now this will just run through without

any problems but we will have a look at

there at the console output as you can

see first we call resource 1 to up we

call these was 2 to up and then we

closer to resources and then the finally

Clause is executed right you can see the

output is coming down here so when we

enter the final Clause the resources

have already been closed for us the

exception handling semantics of the

finally clause are slightly different

then they are from the rest of the tribe

with with resources plug-in that

exceptions thrown from the finally block

are normally not will normally shadow

for any exception thrown earlier but in

order to demonstrate this let me just

put this into a method like this

okay I call this work on resource which

can which may throw an exception it's

not doing that right now but I will make

it do that in a moment let's just throw

e out

so this is kind of simulating that I'm

catching the exception maybe doing some

logging or whatever and then I pre throw

the exception to break the the execution

flow all the way up the cold stack and

then down here in finally I will also

simulate that something happened that

that causes an exception to be thrown

now let me also just wrap the call to

work on resource inside that a try/catch

block up here so we can we can see how

what exceptions are propagated out of

the work on resource method and like

this and then we will ask it to print

the stack trace out now let's try to run

this example here and see what exception

is thrown out of the work on resource

method so I've run it with a debugger

and when we inspect the exception down

here you can see that it is actually the

exception from exception from finally

which is caught up here now this is not

surprising because at the moment we have

configured the resources not to throw

any exceptions when they are closed no

when you call the duo operation so let's

just change that we will have both of

them throw exceptions when they are

closed both of the resources and then we

will have this first resource also throw

an exception when two up is cold now

let's rerun the example and see what

exception is caught up here and look at

that when you look at Eden here again

it's still the exception from finally

that is caught

and when we look at the suppressed

exceptions stored inside of it they are

the the the list is empty there are no

suppressed exceptions in this exception

here and that demonstrates that in case

you throw an exception from the finally

block of a try with resources construct

then suppress exceptions or exception

thrown earlier from the try block or

suppress exceptions when closing the

resources or any exceptions thrown from

within the cache block they are all

shadowed or ignored they they disappear

so you're not able to see them anymore

so be be aware of that if you decide to

add a finally block to your tribe with

resources construct and if that finally

block can throw exceptions that is all

that I have to show or to demonstrate

about the Java try with resources

construct as mentioned early in this

video there's a link to a textual

version of this tutorial in the

description below the video and I also

have a lot more tutorials on my websites

on tutorials dodging cough calm