~/ learn/ comp-348/ cards/ Worked build: a source viewer that greps
1 of 6

Accept either a URL or a bare IP address as the first argument

Accept either a URL or a bare IP address as the first argument

Answer

URL target; try { target = new URL(arg); } catch (MalformedURLException ex) { InetAddress host = InetAddress.getByName(arg); target = new URL("http://" + host.getHostAddress() + "/"); }

The specific interpretation is tried first; only its failure means the argument might be an address. getByName parses a dotted-quad without a lookup and does a DNS query for a name, throwing UnknownHostException — so the enclosing method declares throws IOException and both failures surface as one.

Harold 4e ch7 §Reading Data from a Server; ch5 §The URL Class; ch4 §The InetAddress Class

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/70c5564f-18af-4b1b-931e-525a439d9359/flashcard utf-8 LF