Adding a little bit more detail to my comments

A try-with block is defined as follows:

try(...) {
   ...
}

where the argument in parenthesis needs to be an instance of java.lang.AutoCloseable. An example is the class java.io.InputStream, which is also the class for System.in.

A try-with attempts to automatically close its provided resource, once the block is left. Depending on the used resource, it closes all its own child resources as well.

Taking your example, you have try(Scanner scanner = new Scanner(System.in)), which uses Scanner as resource. The scanner itself uses System.in as resource. Once the try block is left (when } is reached) it tries to close its resources, which is the Scanner instance. This instance also tries to close its resource, the System.in.

Once System.in is closed, you can't get any input from the console anymore (at least not with some additional work, I think...).

Concretely, in your second example:

while (!input.equals("q")) {
    try(Scanner scanner = new Scanner(System.in)){
            ...
    }  // <--- The block is left, scanner is closed, System.in is closed
} // <-- start a new iteration

Here after just one iteration, System.in gets closed. Sure, you create a new Scanner in the next iteration, but System.in remains closed, that's why you get your exception in this case.

Your third example:

try(Scanner scanner = new Scanner(System.in)){
    while (!input.equals("q")) {
        ...
    } // <-- start a new iteration, while still in the same try block
} // <-- only after the while, your resources are closed

Here you're looping your while, while still being inside try. So no resource gets closed, until you leave while and try. That means, the one Scanner remains intact and with it the one System.in. This allows you to keep reading from the console until you're done looping.

Answer from QBrute on Stack Overflow
Top answer
1 of 3
14

Adding a little bit more detail to my comments

A try-with block is defined as follows:

try(...) {
   ...
}

where the argument in parenthesis needs to be an instance of java.lang.AutoCloseable. An example is the class java.io.InputStream, which is also the class for System.in.

A try-with attempts to automatically close its provided resource, once the block is left. Depending on the used resource, it closes all its own child resources as well.

Taking your example, you have try(Scanner scanner = new Scanner(System.in)), which uses Scanner as resource. The scanner itself uses System.in as resource. Once the try block is left (when } is reached) it tries to close its resources, which is the Scanner instance. This instance also tries to close its resource, the System.in.

Once System.in is closed, you can't get any input from the console anymore (at least not with some additional work, I think...).

Concretely, in your second example:

while (!input.equals("q")) {
    try(Scanner scanner = new Scanner(System.in)){
            ...
    }  // <--- The block is left, scanner is closed, System.in is closed
} // <-- start a new iteration

Here after just one iteration, System.in gets closed. Sure, you create a new Scanner in the next iteration, but System.in remains closed, that's why you get your exception in this case.

Your third example:

try(Scanner scanner = new Scanner(System.in)){
    while (!input.equals("q")) {
        ...
    } // <-- start a new iteration, while still in the same try block
} // <-- only after the while, your resources are closed

Here you're looping your while, while still being inside try. So no resource gets closed, until you leave while and try. That means, the one Scanner remains intact and with it the one System.in. This allows you to keep reading from the console until you're done looping.

2 of 3
0

Try this:

   String input = "";
   try (Scanner scanner = new Scanner(System.in)) {
       while (!input.equals("q")) {
           System.out.print("Input: ");
           input = scanner.nextLine();
           System.out.println("Input was: " + input);
       }
   }

You can use every class thats implements Closeable or AutoCloseable in try-with-resources, When code reaches the end of the try call, It call close() function of the Scanner class in our example.

🌐
Baeldung
baeldung.com › home › java › core java › java – try with resources
Java - Try with Resources | Baeldung
May 11, 2024 - As shown above, the scanner variable is declared final explicitly, so we can use it with the try-with-resources block. Although the writer variable is not explicitly final, it doesn’t change after the first assignment.
Discussions

java - Surrounding a Scanner with try-with-resources - Stack Overflow
I've created a an algorithm to read in a file and check multiple questions of user input. I am using Netbeans, and it is suggesting a try-with-resources. What I'm not sure about is the closing of the More on stackoverflow.com
🌐 stackoverflow.com
try with resources - Does Java scanner implement Closeable? - Stack Overflow
I asked this question yesterday. I think I got the right answer, but one of the other answers left me with a question. If I have code like this: File file = new File("somefile.txt"); try (Scanner ... More on stackoverflow.com
🌐 stackoverflow.com
Why do I have to do a try/catch when I use a .txt file in a scanner?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full - best also formatted as code block You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/learnjava
8
26
July 30, 2022
Resource leak with java.util.Scanner, but closing it causes the program to malfunction.
I do hope that the link works, and that I followed the basic guidelines for this subreddit and reddit in general. If not, I apologize in advance. No need to apologize! You have done everything right! Proper title Correct information Detailed posting of error message Code linked properly + correct code formatter used in the pastebin Clear question I'd say: two thumbs up for a very correct first post! Keep up the good work! (As you see, with a proper post like yours, you'll get quick and thorough response) Happy coding! More on reddit.com
🌐 r/javahelp
14
7
October 29, 2014
🌐
Medium
medium.com › @pawanphanieswar › try-with-resources-in-java-7e2e112f4591
try-with-resources in Java. Do you forget to close your scanner… | by Perla Pawan Phanieswar | Medium
October 7, 2024 - The try-with-resources statement is a feature introduced in Java 7 that allows you to manage resources more efficiently by automatically closing them after they are no longer needed.Typically, the closing of objects is necessary to avoid memory ...
🌐
Programiz
programiz.com › java-programming › try-with-resources
Java try-with-resources (With Examples)
We can declare more than one resource in the try-with-resources statement by separating them with a semicolon ; import java.io.*; import java.util.*; class Main { public static void main(String[] args) throws IOException{ try (Scanner scanner = new Scanner(new File("testRead.txt")); PrintWriter writer = new PrintWriter(new File("testWrite.txt"))) { while (scanner.hasNext()) { writer.print(scanner.nextLine()); } } } }
🌐
W3Schools
w3schools.com › java › java_try_catch_resources.asp
Java try-with-resources
Since Java 7, you can use try-with-resources. It is a special form of try that works with resources (like files and streams).
🌐
Oracle
docs.oracle.com › javase › tutorial › essential › exceptions › tryResourceClose.html
The try-with-resources Statement (The Java™ Tutorials > Essential Java Classes > Exceptions)
See Java Language Changes for a ... and removed or deprecated options for all JDK releases. The try-with-resources statement is a try statement that declares one or more resources....
Find elsewhere
🌐
Kansas State University
textbooks.cs.ksu.edu › cc210 › 10-exceptions › 06-java › 06-resources
Try with Resources :: CC 210 Textbook
June 27, 2024 - That Scanner object is the resource that we are using in our Try with Resources statement. We can add multiple resources to that section, separated by semicolons ;. When the code in the try statement throws an exception, Java will automatically try to close the resources declared in the Try ...
🌐
BeginwithJava
beginwithjava.com › home › coding › try with resources with examples
Try with resources with examples - BeginwithJava
October 7, 2024 - In Java SE 7 or later you can use try-with-resources statement to ensure that each resource is closed at the end of the statement. Following program explains this : import java.io.FileReader; import java.io.IOException; import java.util.InputMismatchException; import java.util.Scanner; public ...
🌐
The Java Bootcamp
javapro.academy › home › java blog › core java › try with resources tutorial
Try with Resources Tutorial – The Java Bootcamp
January 22, 2026 - The Scanner implements AutoCloseable, so try-with-resources handles closing automatically. This is how try-with-resources replaces the traditional and verbose try-catch-finally block—with clean, reliable code. Try-with-resources handles multiple resources by separating them with semicolons: ...
🌐
Rakeshvardan
blog.rakeshvardan.com › understanding-and-using-try-with-resources-in-java
Understanding and Using 'Try-With-Resources' in Java
April 24, 2024 - Using this syntax automatically closes the resources declared within the parentheses when the try block is exited, either normally or via an exception. This ensures that the Scanner object is closed to prevent resource leaks, without needing ...
🌐
Reddit
reddit.com › r/learnjava › why do i have to do a try/catch when i use a .txt file in a scanner?
r/learnjava on Reddit: Why do I have to do a try/catch when I use a .txt file in a scanner?
July 30, 2022 -

I am a relative beginner, and I do not understand why do I have to do this. Almost everything can throw an exception all the time. Why do I have to do this in order to use it at all?

Top answer
1 of 7
17
Because Java has checked exceptions - I.e. exceptions that you need to deal with. A good rundown on that can be found here: https://www.baeldung.com/java-checked-unchecked-exceptions In the link above, they quote the java documentation, which does a good job explaining it: If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception. Here, the people that wrote the scanner decided that it can be reasonably be expected that your application should be able to recover from that error. However, it can be difficult to say the exact reason why the scanner's exception specifically is checked.
2 of 7
2
The technical answer is: checked exceptions. However, to answer your broader question: "Why do I have to do this in order to use it at all?", you might start here . Kotlin specifically chose not to support checked exceptions, and long experience with Java has provided a variety of reasons that checked exceptions may have ended up being a mistake. If you want to avoid the try-catch because you don't really have anything reasonable to do in the catch block—meaning you don't have a way of handling the exception other than crashing—you can always add a throws clause to your main method, assuming that's where you're creating the Scanner. If main throws, the program will crash, which may be what you're going to do in your catch block anyway. Although eventually if you want someone else to use your program, you may want to print a reasonable error message ("Could not find required file foo.txt.") rather than just emitting a stack trace. It is true that many Java methods that deal with the filesystem and I/O will generate checked exceptions, because there are a lot of ways for these operations to go wrong.
🌐
Medium
medium.com › thefreshwrites › how-to-use-try-with-resource-in-java-9c0b4ae48d21
How To Use Try With Resource In Java | Exception Handing | by Mouad Oumous | The Fresh Writes | Medium
February 17, 2024 - The Java try with resources construct, is an exception handling mechanism that can automatically close resources like a Java InputStream.
🌐
Zero To Mastery
zerotomastery.io › blog › try-catch-java
Beginner's Guide To Try And Catch In Java | Zero To Mastery
If the file doesn’t exist, Java throws a FileNotFoundException, and the catch block prints "File not found" The finally block runs no matter what happens and closes the scanner to free up system resources · Even if an error occurs, the scanner will always be closed. ... Without finally, you’d have to repeat cleanup code in both the try ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › try-with-resources-feature-in-java
Try-with-resources Feature in Java - GeeksforGeeks
July 23, 2025 - The exceptions thrown by try-with-resources are suppressed, i.e. we can say that try-with-resources block throws suppressed exceptions. Now, let us discuss both the possible scenarios which are demonstrated below as an example as follows: ... // Java Program for try-with-resources // having single resource // Importing all input output classes import java.io.*; // Class class GFG { // Main driver method public static void main(String[] args) { // Try block to check for exceptions try ( // Creating an object of FileOutputStream // to write stream or raw data // Adding resource FileOutputStream fos = new FileOutputStream("gfgtextfile.txt")) { // Custom string input String text = "Hello World.
🌐
Tutorialspoint
tutorialspoint.com › java › java_try_with_resources.htm
Java - Try with Resources
In this program, we're creating the FileReader object within try with resources statement. FileReader fr, reference is declared within the try statement and we need not to remember to close it in finally block as it will be closed automatically by JVM so that there is no memory leak or loose connection possibility. import java.io.FileReader; import java.io.IOException; public class Try_withDemo { public static void main(String args[]) { try(FileReader fr = new FileReader("E://file.txt")) { char [] a = new char[50]; fr.read(a); // reads the contentto the array for(char c : a) System.out.print(c); // prints the characters one by one } catch (IOException e) { e.printStackTrace(); } } }
🌐
Medium
mmarcosab.medium.com › how-about-try-with-resources-cd9cb08d5dc0
How about try-with-resources?. This is a small but useful text about… | by Marcos | Medium
October 9, 2022 - This feature was introduced in Java 7 and allows to declare resources in a try catch block given the security that the resource will be closed after execution of the code block. It’s important to say that the resources need to implement ...
🌐
UTK
web.eecs.utk.edu › ~bvanderz › cs365 › examples › datacheck.html
Using Java's Scanner and Console Class to Read Input
Hence the infinite loop that I ... == null) break; // The following try is a so-called "try block with resources". It automatically // closes the resource when the try block exits. I have used continue // statements in this loop and the try block guarantees that the // ...
🌐
Mkyong
mkyong.com › home › java › java try-with-resources example
Java try-with-resources example - Mkyong.com
November 15, 2022 - We can solve this by wrapping the close stream with another layer of try-catch, but it’s too lengthy and error-prone. In Java 7, we can use try-with-resources to ensure resources after the try block are automatically closed.