Variants

Figure 503. Just finally, no catch Slide presentation Create comment in forum
Scanner scanner = null;
try {
  scanner = new Scanner(System.in);
   ... // Something may fail
} finally {
  if (null != scanner) {
    scanner.close(); // Clean up, save resources!
  }
}

Figure 504. try-with-resources (Java 7) Slide presentation Create comment in forum
try (final Scanner  scanner = new Scanner(System.in)) {
   ... // Something may fail
}

Class must implement interface AutoCloseable.

Variable scanner's scope limited to block.

close() method will be called automatically before leaving block scope.