- 1AclNotFoundException in Java
- 2ActivationException in Java
- 3AlreadyBoundException in Java
- 4ApplicationException in Java
- 5AWTException in Java
- 6BackingStoreException in Java
- 7BadAttributeValueExpException in Java
- 8BadBinaryOpValueExpException in Java
- 9BadLocationException in Java
- 10BadStringOperationException in Java
- 11BrokenBarrierException in Java
- 12CertificateException in Java
- 13CloneNotSupportedException in Java
- 14DataFormatException in Java
- 15DatatypeConfigurationException in Java
- 16DestroyFailedException in Java
- 17ExecutionException in Java
- 18ExpandVetoException in Java
- 19FontFormatException in Java
- 20GeneralSecurityException in Java
- 21GSSException in Java
- 22IllegalClassFormatException in Java
- 23InterruptedException in Java
- 24IntrospectionException in Java
- 25InvalidApplicationException in Java
- 26InvalidMidiDataException in Java
- 27InvalidPreferencesFormatException in Java
- 28InvalidTargetObjectTypeException in Java
- 29IOException in Java
- 30JAXBException in Java
- 31JMException in Java
- 32KeySelectorException in Java
- 33LambdaConversionException in Java
- 34LastOwnerException in Java
- 35LineUnavailableException in Java
- 36MarshalException in Java
- 37MidiUnavailableException in Java
- 38MimeTypeParseException in Java
- 39NamingException in Java
- 40NoninvertibleTransformException in Java
- 41NotBoundException in Java
- 42NotOwnerException in Java
- 43ParseException in Java
- 44ParserConfigurationException in Java
- 45PrinterException in Java
- 46PrintException in Java
- 47PrivilegedActionException in Java
- 48PropertyVetoException in Java
- 49ReflectiveOperationException in Java
- 50RefreshFailedException in Java
- 51RemarshalException in Java
- 52RuntimeException in Java
- 53SAXException in Java
- 54Java ScriptException
- 55Java ServerNotActiveException
- 56Java SOAPException
- 57Java SQLException
- 58Java TimeoutException
- 59Java TooManyListenersException
- 60Java TransformerException
- 61Java TransformException
- 62Java UnmodifiableClassException
- 63Java UnsupportedAudioFileException
- 64Java UnsupportedCallbackException
- 65Java UnsupportedFlavorException
- 66Java UnsupportedLookAndFeelException
- 67Java URIReferenceException
- 68Java URISyntaxException
- 69Java UserException – Custom Exceptions with Examples
- 70Java XAException
- 71Java XMLParseException – XML Parsing and Exception Handling
- 72Java XMLSignatureException
- 73Java XMLStreamException – StAX Parsing Examples
- 74Java XPathException – Complete Guide with Examples
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 messagegetInput()
– The string that caused the exceptiongetReason()
– Human-readable explanationgetIndex()
– 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
Exception | When It Occurs |
---|---|
URISyntaxException | Invalid string used to create a URI |
MalformedURLException | Invalid string used to create a URL object |
Try-Catch | General 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.
Comments
Loading comments...