Java : URISyntaxException with Examples

URISyntaxException (Java SE 21 & JDK 21) with Examples.
You will find code examples on most URISyntaxException methods.


Summary

Checked exception thrown to indicate that a string could not be parsed as a URI reference.

Class diagram

try {
    final var uri = new URI("★://example.com/");
} catch (URISyntaxException e) {
    System.out.println("URISyntaxException! : " + e.getMessage());
}

// Result
// ↓
//URISyntaxException! : Illegal character in scheme name at index 0: ★://example.com/

Constructors

URISyntaxException (String input, String reason)

Constructs an instance from the given input string and reason.

final var e = new URISyntaxException("abc", "XYZ");
System.out.println(e); // java.net.URISyntaxException: XYZ: abc

URISyntaxException (String input, String reason, int index)

Constructs an instance from the given input string, reason, and error index.

final var e = new URISyntaxException("abc", "XYZ", 123);
System.out.println(e); // java.net.URISyntaxException: XYZ at index 123: abc

Methods

int getIndex ()

Returns an index into the input string of the position at which the parse error occurred, or -1 if this position is not known.

final var e = new URISyntaxException("abc", "XYZ", 123);
System.out.println(e.getMessage()); // XYZ at index 123: abc
System.out.println(e.getInput()); // abc
System.out.println(e.getReason()); // XYZ
System.out.println(e.getIndex()); // 123

String getInput ()

Returns the input string.

final var e = new URISyntaxException("abc", "XYZ", 123);
System.out.println(e.getMessage()); // XYZ at index 123: abc
System.out.println(e.getInput()); // abc
System.out.println(e.getReason()); // XYZ
System.out.println(e.getIndex()); // 123

String getMessage ()

Returns a string describing the parse error.

final var e = new URISyntaxException("abc", "XYZ", 123);
System.out.println(e.getMessage()); // XYZ at index 123: abc
System.out.println(e.getInput()); // abc
System.out.println(e.getReason()); // XYZ
System.out.println(e.getIndex()); // 123

String getReason ()

Returns a string explaining why the input string could not be parsed.

final var e = new URISyntaxException("abc", "XYZ", 123);
System.out.println(e.getMessage()); // XYZ at index 123: abc
System.out.println(e.getInput()); // abc
System.out.println(e.getReason()); // XYZ
System.out.println(e.getIndex()); // 123

Methods declared in Throwable

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

Please see the link below.


Related posts

To top of page