Catch Invalid path exception in Java

Description

The following code shows how to catch Invalid path exception.

Example


// ww w . jav a2  s. c o  m
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {

  public static void main(String[] args) {
    try {
      Path path = Paths.get("/home\0", "docs", "users.txt");
      System.out.println("Absolute path: " + path.toAbsolutePath());
    } catch (InvalidPathException ex) {
      System.out.println("Bad path: [" + ex.getInput() + "] at position "
          + ex.getIndex());
    }

  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    I/O »




Binary File
Byte Array
CharSet
Checksum
Console
Create Copy Move Delete
Directory
Drive
Encode Decode
File Attribute
File Lock
File System
GZIP
Jar File
NIO Buffer
Path
Scanner
StreamTokenizer
Temporary File
Text File
Zip