Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

MalformedURLException — URL construction failure

MalformedURLException is a checked exception in java.net that extends IOException. It signals a URL construction problem, such as an unrecognized protocol or input rejected by its handler; it does not mean that a connection failed.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

public class MalformedURLException extends IOException

public MalformedURLException()
public MalformedURLException(String msg)

MalformedURLException, in package java.net, signals an invalid URL specification: no legal protocol was found or the specification could not be parsed. It extends IOException and is checked: code calling a method that declares it must catch it or declare it with throws.

The class provides MalformedURLException() without a detail message and MalformedURLException(String msg) with the supplied message. Do not confuse this exception with a DNS failure, a refused connection, or an HTTP error response. Constructing a URL object alone establishes neither resource availability nor complete address validity; some validation depends on the protocol handler.

In Java SE 21, the URL constructors are deprecated. The recommended path is to create a URI and then call URI.toURL(). That method can throw MalformedURLException when the protocol is unknown or conversion fails. A relative URI, however, causes IllegalArgumentException. Invalid syntax passed to URI.create(...) also causes IllegalArgumentException, whereas the new URI(...) constructor throws URISyntaxException.

The example converts a constant, absolute URI using the https protocol into a URL, catches MalformedURLException, and prints the protocol. It opens no network connection. For this input, the expected output is https; the catch branch is not executed.

Examples

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;

public class Main {
    public static void main(String[] args) {
        URI uri = URI.create("https://example.com/docs");
        try {
            URL url = uri.toURL();
            System.out.println(url.getProtocol());
        } catch (MalformedURLException e) {
            System.out.println("Cannot construct URL");
        }
    }
}

Result

https

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources