How to define an explicit constructor for a url object in Java

I define url in processing (or java) with a line:

URL base = new URL("http://www.google.com/");

      

So I'm getting the following error: The default constructor cannot handle the MalformedURLException exception type thrown by the implicit super constructor. An explicit constructor must be defined. I am guessing that if my url is invalid, there is no appropriate catch

one to catch the error (because I am declaring my url out try

).

But I want to define this url outside try

because my main block try

is in a loop and the url is static. So there is no need to do the URL definition more than once (and because it is static, I am not afraid of any MalformedURLExceptions).

How should I do it? Is there no other way other than defining the URL in a separate block try

? (because it seems too big for a simple static url)


// import libraries
import java.net.*;
import java.io.*;

// url
URL base = new URL("http://www.google.com");

void setup() {
}

void draw() {
  try {
    // retrieve url
    String[] results = loadStrings(base);

    // print results
    println(results[0]);
  }  
  catch (MalformedURLException e) {
    e.printStackTrace();
  }
  catch (ConnectException e) {
    e.printStackTrace();
  }
  catch (IOException e) {
    e.printStackTrace();
  }

  // stop looping
  noLoop();

}

      

+3


source to share


2 answers


You just need to define a default constructor for your class that throws the MalformedURLException:

class MyClass {
    private URL url = new URL("http://www.google.com");

    public MyClass() throws MalformedURLException {}
}

      

The error occurs because the Java constructor generates for your class cannot throw anything, you have to specify what it can.



Edit

Seeing your code, another option is this (I assume setup () is called before using the url)

URL url;

void setup() {
    try {
        url = new URL("http://www.google.com");
    } catch (MalformedURLException ex) {
        throw new RuntimeException(ex);
    }
}

      

+12




Since the constructor URL

throws a checked exception , you must either catch it or reverse engineer it . You can create your own factory method that simply wraps it in RuntimeException

:

public class URLFactory {
  public static URL create(String urlString) {
    try {
      return new URL(urlString);
    } catch (MalformedURLException e) {
      throw new RuntimeException(e);
    }
  }
}

      

Or maybe it's just in your environment?



URL createURL(String urlString) {
  try {
    return new URL(urlString);
  } catch (MalformedURLException e) {
    throw new RuntimeException(e);
  }
}

      

And use instead:

URL base = URLFactory.create("http://www.google.com");

      

+1


source







All Articles