Java : IOException with Examples

IOException (Java SE 22 & JDK 22) in Java with Examples.
You will find code samples for most of the IOException methods.


Summary

Signals that an I/O exception of some sort has occurred. This class is the general class of exceptions produced by failed or interrupted I/O operations.

Class diagram

final var path = Path.of("R:", "java-work", "aaa.txt");
System.out.println(path); // R:\java-work\aaa.txt

System.out.println(Files.notExists(path)); // true

try {
    final var str = Files.readString(path);
} catch (IOException e) {
    System.out.println(e);
}

// Result
// ↓
//java.nio.file.NoSuchFileException: R:\java-work\aaa.txt

Constructors

IOException ()

Constructs an IOException with null as its error detail message.

final var e = new IOException();
System.out.println(e); // java.io.IOException

IOException (String message)

Constructs an IOException with the specified detail message.

final var e = new IOException("abcd");
System.out.println(e); // java.io.IOException: abcd
System.out.println(e.getMessage()); // abcd

IOException (String message, Throwable cause)

Constructs an IOException with the specified detail message and cause.

final var cause = new IOException("XYZ");
final var e = new IOException("abcd", cause);

System.out.println(e); // java.io.IOException: abcd
System.out.println(e.getMessage()); // abcd

System.out.println(e.getCause()); // java.io.IOException: XYZ
System.out.println(e.getCause().getMessage()); // XYZ

IOException (Throwable cause)

Constructs an IOException with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause).

final var cause = new IOException("XYZ");
final var e = new IOException(cause);

System.out.println(e); // java.io.IOException: java.io.IOException: XYZ

System.out.println(e.getCause()); // java.io.IOException: XYZ
System.out.println(e.getCause().getMessage()); // XYZ

Methods declared in Throwable

addSuppressed, fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, getSuppressed, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString

Please see the link below.


Related posts

To top of page