1

When executing an HttpUriRequest using the AndroidHttpClient, it will throw an java.lang.IllegalArgumentException: Host name may not be null when the url is faulty.

In my application, the user can input his own url. When for example http://195.168.0.q is entered, the IllegalArgument is thrown, and the app crashes.

How can I prevent this (preferably, without catching exceptions)?

nhaarman
  • 98,571
  • 55
  • 246
  • 278
  • @MarcoAcierno Does there even exist a regex which covers all possible correct url's? – nhaarman May 04 '14 at 19:18
  • What kind of urls you except? – Marco Acierno May 04 '14 at 19:26
  • Everything `HttpClient` accepts. – nhaarman May 04 '14 at 19:27
  • There is already a class that handles parsing of URLs and throws a very specific exception if it is not formed correctly (```MalformedURLException```). I don't think re-inventing that is a good idea. I don't think this is against coding standards, I think it is exactly why this exception class was created. – myanimal May 04 '14 at 20:05

2 Answers2

0

Catch the exception with a 'try-catch(-finally)' block.

try {
   // your code
} catch(IllegalArgumentException) {
   // Faulty url
}
Dávid Szabó
  • 2,235
  • 2
  • 14
  • 26
0

You should make sure the user has supplied a valid URL before trying to use it as one:

URL url;
try {
    url = new URL("http://195.168.0.q");
} catch (MalformedURLException e) {
    // tell user the URL they entered is invalid
}
myanimal
  • 3,580
  • 26
  • 26