Technically it's possible. For example, consider this program:
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
public class Test {
public static void main(String[] args) throws MalformedURLException {
URL.setURLStreamHandlerFactory(protocol -> {
throw new UnsupportedOperationException();
});
System.out.println(new File("/etc/passwd").toURI().toURL());
}
}
Here toURL
call actually fails with MalformedURLException
:
Exception in thread "main" java.net.MalformedURLException
at java.net.URL.<init>(URL.java:627)
at java.net.URL.<init>(URL.java:490)
at java.net.URL.<init>(URL.java:439)
at java.net.URI.toURL(URI.java:1089)
at com.example.Test.main(Test.java:20)
Caused by: java.lang.UnsupportedOperationException
at com.example.Test.lambda$main$0(Test.java:17)
at java.net.URL.getURLStreamHandler(URL.java:1142)
at java.net.URL.<init>(URL.java:599)
... 4 more
However I doubt that your program will function correctly anyways if you set custom URLStreamHandlerFactory
which does not support even file
scheme.
With default URLStreamHandlerFactory
I cannot think up or remember cases when toURL
may fail, so if you don't mess with URLStreamHandlerFactory
, you can use it safely.
If you need to produce URL
objects often, you may consider creating some utility method like this:
public class FileUtils {
public static URL toURL(File file) {
try {
return file.toURI().toURL();
} catch (MalformedURLException e) {
throw new InternalError(e);
}
}
}
And use it everywhere. It just asserts that MalformedURLException
is impossible in your program, so if it actually occurs, it will be considered as internal program error.
Another possibility is not to use URL
class at all. For many purposes the URI
class can be used instead.