Java Scanner ioException() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
java.util.Scanner

Definition

In Java, sc.ioException() returns the last java.io.IOException thrown by the scanner's underlying Readable source, or null if no I/O error has occurred.

Because Scanner methods like next() and hasNextLine() do not declare throws IOException, Scanner catches any read failure silently, ends input, and stores the exception here.

An instance method of java.util.Scanner, available since Java 5 (JDK 1.5). A Scanner reads from any source (System.in for keyboard, a String, or a file) with identical parsing logic; pass the source to new Scanner(...) after import java.util.Scanner; and call sc.ioException(...).

Syntax

Check sc.ioException() after your reading loop ends to confirm whether input ended normally or due to a read error.

Java
while (sc.hasNextLine()) {
    process(sc.nextLine());
}
IOException err = sc.ioException();   // null if no I/O error occurred
CallWhat it does
sc.ioException()Returns the stored IOException, or null when none happened.

Over an in-memory String or healthy StringReader, sc.ioException() always returns null.

Library declarations
Java
// java.util.Scanner
public IOException ioException()

Parameters

ParameterDescription
NoneioException() takes no parameters.

Return Value

Return ValueDescription
IOExceptionThe last IOException thrown by the underlying source (including on close()), or null.

Compare with Similar Methods

Error handling and resource closing:

MethodHow it differs
close()Closes a Closeable source; captures close errors into ioException().
hasNext()Quietly returns false if an underlying read throws IOException.
Files.newBufferedReader()Throws checked IOException directly instead of hiding it.

Java Examples

Example 1 — Check ioException() After a Normal String and StringReader Scan

Confirm that reading cleanly from a String or StringReader leaves sc.ioException() equal to null.

Java
import java.io.StringReader;
import java.util.Scanner;

public class ScannerIoExceptionNull {
    public static void main(String[] args) {
        try (Scanner s1 = new Scanner("one two");
             Scanner s2 = new Scanner(new StringReader("three four"))) {
            while (s1.hasNext()) { s1.next(); }
            while (s2.hasNext()) { s2.next(); }
            System.out.println("String ioException:       " + s1.ioException());
            System.out.println("StringReader ioException: " + s2.ioException());
        }
    }
}

How It Works

  1. In-memory text never hits I/O errors. Scanning "one two" finishes cleanly with null stored.
  2. Healthy Reader also stays null. Even after exhausting StringReader, no IOException occurs.
  3. Safe check after loop. Testing ioException() == null confirms the loops saw true end of data.

Example 2 — Catch a Hidden IOException Thrown Mid-Read by a Failing Readable

Wrap a custom Readable that delivers one word and then throws IOException so you can see sc.ioException() catch it.

Java
import java.io.IOException;
import java.nio.CharBuffer;
import java.util.Scanner;

public class ScannerIoExceptionRead {
    public static void main(String[] args) {
        Readable failing = new Readable() {
            int calls = 0;
            public int read(CharBuffer cb) throws IOException {
                calls++;
                if (calls == 1) {
                    cb.append("first ");
                    return 6;
                }
                throw new IOException("disk offline");
            }
        };
        try (Scanner sc = new Scanner(failing)) {
            while (sc.hasNext()) {
                System.out.println("Read token: " + sc.next());
            }
            if (sc.ioException() != null) {
                System.out.println("Caught error: " + sc.ioException().getMessage());
            }
        }
    }
}

How It Works

  1. First chunk succeeds. The custom Readable feeds "first " so sc.next() returns "first".
  2. Second read throws silently. Scanner catches IOException("disk offline") internally and stops hasNext() with false.
  3. ioException() reveals the failure. Inspecting sc.ioException() recovers the exact message "disk offline".

Example 3 — Inspect ioException() After Closing a Closeable Source

See how Scanner.close() stores any IOException thrown while closing the source, and still lets you read sc.ioException() afterwards.

Java
import java.io.Closeable;
import java.io.IOException;
import java.nio.CharBuffer;
import java.util.Scanner;

public class ScannerIoExceptionClose {
    static class BrokenCloseSource implements Readable, Closeable {
        public int read(CharBuffer cb) { return -1; }
        public void close() throws IOException {
            throw new IOException("close failed");
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(new BrokenCloseSource());
        System.out.println("Any tokens? " + sc.hasNext());
        sc.close();
        IOException err = sc.ioException();
        System.out.println("After close: " + (err != null ? err.getMessage() : "none"));
    }
}

How It Works

  1. Normal EOF before closing. The empty Readable returns -1 immediately so hasNext() is false.
  2. close() catches IOException internally. sc.close() does not declare throws IOException; it records "close failed" instead.
  3. Readable even after close(). Calling sc.ioException() after closing still retrieves the stored exception without throwing IllegalStateException.

Frequently Asked Questions

Because Scanner wraps Readable sources that can fail with IOException, catches those exceptions internally so loops stay simple, and saves the last one for ioException().
Always null, because scanning an in-memory String cannot raise an I/O error.
No. You can inspect sc.ioException() after sc.close(), which is also how you detect errors thrown during close().
Yes. If sc.ioException() is non-null after the loop ends, an I/O failure cut reading short rather than normal end-of-file.
No. Only IOException instances thrown by the underlying Readable or Closeable appear in ioException().

Next: locale()

Return the Locale used when parsing numbers.

locale() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

13 people found this page helpful