using try resouce

Refactoring the finally and using the try-resource.