MalformedURLException when creating URL?
Hi. Does anyone know why Netbeans 5.5 gives me a MalformedURLException EVERY time I write code to create a URL?
It red-underlines my code and says "unreported exception java.net.MalformedURLException; must be caught or declared to be thrown".
I haven't even run my code yet... There is nothing wrong with the URL or the String object (if applicable) I am using. It doesn't matter whether I use a valid URI's .toURL() method, or if I use anew URL(anotherURL.toString())
.
If I enclose the whole thing in a try...catch, it takes away the red-underline and it works just fine when I run it... even though it never catches the exception.
Is this a NetBeans bug, a Java bug, or should I just be doing something differently?
Thanks for any feedback...
-RN
> If I enclose the whole thing in a try...catch, it
> takes away the red-underline and it works just fine
> when I run it... even though it never catches the
> exception.
Thus goes the pain of Java.
The MalformedURLException is a checked Exception, and thus must be caught by any code calling the URL() constructor. Compile it on the command line, and javac will tell you the same. Only those exceptions that extend RuntimeException are deemed "Unchecked", and hence allowed to transcend main().
http://www.freshsources.com/Apr01.html
> > I also have to ask why are you writing "new
> URL(anotherURL.toString())"?
>
> I was just trying to make the point that my String
> argument did not have a flaw... it came from a valid
> URL, but it was still being discriminated against :-(
Show the real code please. Show the real URL please. If URLs discriminate, it is only because they have good taste, not because they are prejudiced.
MalformedURLException is totally miscategoized. It should be a subclass of RuntimeException but instead it got released in the first version of java that there ever was as a checked exception... so you have to catch it. This is actually one of my biggest annoyances in Java. Not only is it stupid to have to catch MalformedURLException every time you create a URL from a String, but even stupider is that because there's no way to construct a URL without catching that exception, you now also have to catch it on File.toURL() When is File.toURL() going to throw an exception? Answer: Never. But still you need to catch it.
I think of these kinds of things as annoyances, but one-time annoyances. Write a utility method:
public static URL newURL(String spec) throws MyRuntimeMalformedURLException {// unchecked
try {
return new URL(spec);
} catch (MalformedURLException e) {
throw new MyRuntimeMalformedURLException(e);
}
}