Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an utility to parse an URL without checked exception in java?

EDIT: Seems that I sounded too annoyed in the first, here is a rework.

I'd like to create an URL constant, like so

public static final URL REMOTE_URL = new URL("http://example.com/");

But I can't since the constructor throw a checked exception. Right now I use

public static final URL REMOTE_URL = createUrl("http://example.com/");

private static URL createUrl(String url) {
    try {
        return new URL(url);
    } catch (MalformedURLException error) {
        throw new IllegalArgumentException(error.getMessage(), error);
    }
}

But it feel like reinventing the wheel. I can't possibly be the only one who want to use a URL constant no? So I was wondering if there is third-party toolbox library (like guava or apache-commons, or something else, anything) or even better, something in standard Java that include this facilities? That would help me when we start a new project by reducing the size of our util package :) .

like image 319
Laurent Bourgault-Roy Avatar asked Sep 26 '13 18:09

Laurent Bourgault-Roy


People also ask

How does Java handle checked and unchecked exceptions?

A checked exception is caught at compile time whereas a runtime or unchecked exception is, as it states, at runtime. A checked exception must be handled either by re-throwing or with a try catch block, whereas an unchecked isn't required to be handled.

What are the methods in the URL class used for parsing the URL?

The URL class provides several methods that let you query URL objects. You can get the protocol, authority, host name, port number, path, query, filename, and reference from a URL using these accessor methods: getProtocol.

What is a URL parser?

URL Parsing. The URL parsing functions focus on splitting a URL string into its components, or on combining URL components into a URL string.


1 Answers

This complaint must have been a common one, because Java has (since 1.7) introduced the URI class. This class has two ways of constructing it:

  1. Using URI.new, which throws a checked exception
  2. Using URI.create, which throws an unchecked exception

For URIs/URLs like yours that are known to come from a safe source, you can use the URI.create() variant and not have to worry about catching the exception as you know it won't be thrown.

Unfortunately, sometimes you can't use a URI and you still need a URL. There's no standard method (that I have found so far) of converting a URI into a URL that doesn't throw a checked exception.

like image 106
Fr Jeremy Krieg Avatar answered Sep 17 '22 20:09

Fr Jeremy Krieg