java.net.URISyntaxException – How to solve URISyntaxException
In this example we are going to talk about java.net.URISyntaxException
. This is a checked exception that occurs when you are trying to parse a string that represents a URI, but it doesn’t have the correct format.
1. A simple example of URISyntaxException
Let’s see a program that parses a legal URI:
URISyntaxExceptioExample.java:
package com.javacodegeeks.core.net.urisyntaxexception; import java.net.URI; import java.net.URISyntaxException; public class URISyntaxExceptioExample { public static void main(String[] args) { try { URI uri = new URI("http://www.javacodegeeks.com/"); System.out.println("URI parsed succesfully!"); } catch (URISyntaxException e) { e.printStackTrace(); } } }
This will output:
URI parsed succesfully!
Now let’s add an illegal character to the URI, let’s say a space. So let’s change:
URI uri = new URI("http://www.javacodegeeks.com/");
to
URI uri = new URI("http://www. javacodegeeks.com/");
If you run this, it will output:
java.net.URISyntaxException: Illegal character in authority at index 7: http://www. javacodegeeks.com/ at java.net.URI$Parser.fail(URI.java:2829) at java.net.URI$Parser.parseAuthority(URI.java:3167) at java.net.URI$Parser.parseHierarchical(URI.java:3078) at java.net.URI$Parser.parse(URI.java:3034) at java.net.URI.(URI.java:595) at com.javacodegeeks.core.net.urisyntaxexception.URISyntaxExceptioExample.main(URISyntaxExceptioExample.java:12)
As you can see, URISyntaxException
is accompanied with a very informative message that tells you where exactly the problem is.
2. How to solve URISyntaxException
To avoid this exception, it is important to to perform checks against the strings you want to parse. You can do that using regular expressions. Additionally, you should try to perform URI encoding before parsing your strings. This process, will remove illegal characters from the strings and on the same time encode special character to the correct format.
Download Source Code
This was an example on java.net.URISyntaxException
and how to solve URISyntaxException
. You can download the source code of this example here : URISyntaxExceptionExample.zip