Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unreported exception MalformedURLException when creating a URL

Tags:

java

Excuse me for my lack of Java skills, but I am normally a C kind of person.. I am beginning some Android development and I want to simply make a GET request. However, I cannot even get a simple URL type to compile correctly. I keep getting this error:

HelloWorld.java:17: error: unreported exception MalformedURLException; must be caught or declared to be thrown
 URL url = new URL("http://www.google.com/");
 ^
1 error

When running this simple code:

 import java.io.BufferedReader;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.InputStreamReader;
 import java.io.OutputStream;
 import java.io.OutputStreamWriter;
 import java.io.Reader;
 import java.io.Writer;
 import java.net.HttpURLConnection;
 import java.net.ProtocolException;
 import java.net.URL;
 import java.net.URLConnection;

public class HelloWorld{

     public static void main(String []args){
        URL url = new URL("http://www.google.com/");

        System.out.println(url.toString());
     }
}

What am I doing wrong here?

like image 697
Matt Hintzke Avatar asked Jul 18 '13 20:07

Matt Hintzke


People also ask

How do I fix MalformedURLException?

Handling MalformedURLException The only Solution for this is to make sure that the url you have passed is legal, with a proper protocol. The best way to do it is validating the URL before you proceed with your program. For validation you can use regular expression or other libraries that provide url validators.

What causes a MalformedURLException?

A MalformedURLException is thrown when the built-in URL class encounters an invalid URL; specifically, when the protocol that is provided is missing or invalid.

What specific exception is produced if an unknown URL protocol is specified?

MalformedURLException - if an unknown protocol is specified. See Also: URL(java.

What is a malformed URL?

This violation indicates that a request that was not created by a browser, and does not comply with HTTP standards, has been sent to the server. This may be the result of of an HTTP request being manually crafted or of a client tunneling other protocols over HTTP.


1 Answers

For all checked exception, it becomes mandatory to handle them in your code. here are 2 ways to do that.

in general, you can either pass on the exception handling to caller of the declaring method using throws clause. or you can handle them there itself using try-catch[-finally] construct.

in your case, you either need to add throws clause to main() method as

public static void main(String []args) throws MalformedURLException{

or you need to surround URL declaration with try-catch block, like here:

try{
    URL url = new URL("http://www.google.com/");
    //more code goes here
}catch(MalformedURLException ex){
//do exception handling here
}
like image 72
Ankit Avatar answered Sep 24 '22 19:09

Ankit