Java URISyntaxException

Introduction to URISyntaxException

Java provides a robust java.net.URI class for handling Uniform Resource Identifiers (URIs), which are used to locate resources like files, websites, or API endpoints. But not all strings are valid URIs. If you try to create a URI object using an invalid string, Java throws a URISyntaxException.

This tutorial walks you through the URISyntaxException in Java — what it means, how and when it happens, and how to avoid or handle it. You'll learn with complete, beginner-friendly examples and step-by-step guidance to write URI-safe Java code.

What is URISyntaxException?

URISyntaxException is a checked exception in the java.net package. It is thrown to indicate that a string could not be parsed as a valid URI reference.

public class URISyntaxException extends Exception

It typically occurs when creating a new URI instance from a malformed string:

URI uri = new URI("http:/example.com"); // Missing slash

Why URISyntaxException Happens

Some common reasons:

  • Missing components (like scheme, host, or slashes)
  • Illegal characters (spaces, unescaped characters)
  • Wrong format (too many colons, invalid query syntax)

Basic Example: Triggering URISyntaxException

import java.net.URI;
import java.net.URISyntaxException;

public class URISyntaxExample {
    public static void main(String[] args) {
        try {
            URI uri = new URI("https:banana.com//item 1"); // space and double slash
            System.out.println("Valid URI: " + uri);
        } catch (URISyntaxException e) {
            System.out.println("Caught URISyntaxException:");
            System.out.println("Reason: " + e.getReason());
            System.out.println("Input: " + e.getInput());
            System.out.println("Error Index: " + e.getIndex());
        }
    }
}

Expected Output:

Caught URISyntaxException:
Reason: Illegal character in path at index 21
Input: https:banana.com//item 1
Error Index: 21

In this example, the space in "item 1" violates URI syntax rules and triggers the exception.

How to Avoid URISyntaxException

1. Use Proper Encoding for Unsafe Characters

Unsafe characters like spaces should be encoded. Use URLEncoder for query parameters or manual replacement for paths:

String safePath = "item%201"; // Replace space with %20
URI uri = new URI("https://banana.com/" + safePath);

2. Validate Input Before Creating URI

Simple checks like String.contains(" ") or using regex can help sanitize inputs.

3. Catch the Exception Gracefully

Wrap your URI creation in a try-catch block to handle unexpected formats without crashing the app.

Working with URI Components

try {
    URI uri = new URI("https", "www.apple.com", "/products", "type=fruit", null);
    System.out.println("Constructed URI: " + uri);
} catch (URISyntaxException e) {
    System.out.println("Invalid URI components.");
}

Output:

Constructed URI: https://www.apple.com/products?type=fruit

Using the multi-argument URI constructor reduces the chance of invalid format issues.

Real-World Use Case: Creating API Endpoint URIs

public class APIClient {
    public static void main(String[] args) {
        String baseUrl = "https://api.fruits.com";
        String path = "/query";
        String query = "name=cherry&type=red fruit";

        try {
            URI uri = new URI(baseUrl + path + "?" + query.replace(" ", "%20"));
            System.out.println("Request URI: " + uri);
        } catch (URISyntaxException e) {
            System.err.println("Failed to build URI: " + e.getMessage());
        }
    }
}

Output:

Request URI: https://api.fruits.com/query?name=cherry&type=red%20fruit

Understanding the Exception Methods

Useful methods provided by URISyntaxException:

  • getMessage() – Complete error message
  • getInput() – The string that caused the exception
  • getReason() – Human-readable explanation
  • getIndex() – Position in the string where the error was found

Best Practices

  • Always encode special characters in paths and queries
  • Use the URI component constructors instead of raw string concatenation
  • Log or display meaningful exception messages
  • Wrap URI creation in a method with built-in error handling

Comparison with Related Exceptions

ExceptionWhen It Occurs
URISyntaxExceptionInvalid string used to create a URI
MalformedURLExceptionInvalid string used to create a URL object
Try-CatchGeneral Java mechanism for catching checked exceptions

Conclusion

URISyntaxException may be a small exception, but it plays a vital role in ensuring that your Java applications build valid and well-formed URIs.