Unformed MalformedURLException while creating url

Sorry for the lack of Java skills, but I'm usually C person. I am starting Android development and I just want to make a GET request. However, I cannot even get a simple URL type for proper compilation. 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?

+7
java
source share
4 answers

For all checked exceptions, it becomes mandatory to handle them in your code. Here are 2 ways to do it.

in general, you can either pass exception handling to the caller of the declaration method using the throws . or you can process them there using the try-catch[-finally] .

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

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

or you need to surround the url declaration with a try-catch , like here:

 try{ URL url = new URL("http://www.google.com/"); //more code goes here }catch(MalformedURLException ex){ //do exception handling here } 
+16
source share

In java you have to handle exceptions. The easiest way to do this in an example program is to declare main() throw:

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

Get to know the training and look at exception handling issues later.

+3
source share

The URL constructor declares that it can throw an exception, so you need to catch it or throw it back


Cm.

+1
source share

You should wrap the url declaration in try-catch (or throw it away)

Learn more about exception handling.

 URL url; try { url = new URL("http://www.google.com/"); } catch(MalformedURLException e) { System.out.println("The url is not well formed: " + url); } 

this is because creating Url is β€œdangerous” and creating something like:

 new URL("testurl"); 

will throw an exception.

0
source share

All Articles