URISyntaxException

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

Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. During his studies he discovered his interests about software development and he has successfully completed numerous assignments in a variety of fields. Currently, his main interests are system’s security, parallel systems, artificial intelligence, operating systems, system programming, telecommunications, web applications, human – machine interaction and mobile development.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button