Class MalformedURLException in Java

digitization, transformation, binary

Introduction to Class MalformedURLException in Java

MalformedURLException is common exception classes in java when working with a network and is thrown from an application to indicate that a malformed URL has occurred. It happens when the built-in class URL gets an invalid URL.

In a client-server architecture, while connecting, if we use java.net.URL class object then we need to pass the String representation of URL. (This is while establishing a connection.)

Ads code goes here

Now if the URL can not be parsed due to one of the following reasons, then MalformedURLException is thrown.

MalformedURLException is a subclass of IOException and it is a checked Exception.

There could be three scenarios:

  1. No legal  protocol could be found in the specification String
  2. The string could not be parsed.
  3. The URL was not built correctly.

One of the above causes the MalformedURLException.

When to use Class MalformedURLException in Java?

A MalformedURLException(Class MalformedException in Java) is thrown when “no legal protocol could be found in a specification String” or when the provided “String could not be parsed”. This is as per specification.

As modern java supports most of the String manipulation statements via String commands, a MalformedURLException is rarely originated due to String parse error.

So mostly this Exception occurs for legal protocol issue.

URI(Unified Resource Identifier) vs URL(Unified Resource Locator)

URI(Unified Resource Identifier) is a string of consecutive characters that can pick a resource on the Internet. URI can have several different types of schemas just to represents a control the access of any resource.

URL(Unified Resource Locator) is a specific type of URI. A URL is however unique over the internet. Class URL, however, throws the MalformedURLException.

Every URI, regardless if it’s a URL or not, follows a particular form:

scheme:[//authority][/path][?query][#fragment]

Where each part is described as follows:

  • the scheme − for URLs, is the name of the protocol used to access the resource, for other URIs, is a name that refers to a specification for assigning identifiers within that scheme
  • authority − an optional part comprised of user authentication information, a host and an optional port
  • path − it serves to identify a resource within the scope of its scheme and authority
  • query − additional data that, along with the path, serves to identify a resource. For URLs, this is the query string
  • fragment − an optional identifier to a specific part of the resource
READ  IllegalThreadStateException in Java

How to convert URI to URL and Vice versa?

String correctURL="https://techtravelhub.com";
URI myURI=new URI(correctURL);
URL myURL=new URL(correctURL);

URL toConvertURL=myURI.toURL()
URI toConvertURI=myURL.toURI()

But note that if we try to convert a non URL like htt://techtravelhub.com, MalformedURLException will occur.

Precaution for opening a remote URL

As URL is the valid reference(unique) to a remote resource, we can make a connection to the remote resource and fetch its content.

URL myURL=new URL("http://techtravelhub.com");
String URLContents=IOUtils.toString(myURL.openStream());
AssertTrue(URLContents.contains("<DOCTYPE html>"));

The Hierarchy of the Class MalformedURLException in Java

MalformedURLException implements java.lang.Throwable interface.

class MalformedURLException in Java
class MalformedURLException in Java

The class MalformedURLException in Java  is defined as below:

public class java.io.MalformedURLException extends java.lang.IOException{
//constructor
public MalformedURLException();//constructs an empty MalformedURLException object that is an object with no message specified.
public MalformedURLException(String message);//constructs an MalformedURLException object with the message specified.
}

The class MalformedURLException also inherits methods from class Object and Throwable.

From Object classFrom Throwable class
clone()fillInStackTrace()
getClass()getMessage()
notify()printStackTrace()
wait()printStackTrace(PrintWriter)
wait(long, int)getLocalizedMessage()
wait(long)printStackTrace(PrintStream)
equals(Object)
toString()
finalize()
hashCode()
notifyAll()

 

An Example of MalformedURLException(Class MalformedException in Java)

Below is a code for getting this Exception:

import java.util.Scanner;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class MalFormedExceptionExample{
   public static void main(String[] args) throws IOException {
      String url = "hps://www.techtravelhub.com/";
      URL obj = new URL(url);
      //Opening a connection
      HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
      //Sending the request
      conn.setRequestMethod("GET");
      int response = conn.getResponseCode();
      if (response == 200) {
         //Reading the response to a StringBuffer
         Scanner responseReader = new Scanner(conn.getInputStream());
         StringBuffer buffer = new StringBuffer();
         while (responseReader.hasNextLine()) {
            buffer.append(responseReader.nextLine()+"\n");
         }
         responseReader.close();
         //Printing the Response
         System.out.println(buffer.toString());
      }
   }
}

The output of the code is as follows:
Runtime Exception
Exception in thread “main” java.net.MalformedURLException: unknown protocol: htp
at java.net.URL.(Unknown Source)
at java.net.URL.(Unknown Source)
at java.net.URL.(Unknown Source)
at myPackage.MalFormedExceptionExample.main(MalFormedExceptionExample.java:11)

How to solve the MalFormedException?

The best way to solve MalformedException is to put a check on the URL before parsing the URL or go deep with the provided URL.

The checking code is as follows:

public static boolean isUrlValid(String url) {
      try {
         URL obj = new URL(url);
         obj.toURI();
         return true;
      } catch (MalformedURLException e) {
         return false;
      } catch (URISyntaxException e) {
         return false;
      }
   }

While incorporating into the class, the full code looks like below:

import java.util.Scanner;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
public class MalFormedExceptionExample{
   public static boolean isUrlValid(String url) {
      try {
         URL obj = new URL(url);
         obj.toURI();
         return true;
      } catch (MalformedURLException e) {
         return false;
      } catch (URISyntaxException e) {
         return false;
      }
   }
   public static void main(String[] args) throws IOException {
      String url = "ht://www.techtravelhub.com/";
      if(isUrlValid(url)) {
         URL obj = new URL(url);
         //Opening a connection
         HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
         //Sending the request
         conn.setRequestMethod("GET");
         int response = conn.getResponseCode();
         if (response == 200) {
            //Reading the response to a StringBuffer
            Scanner responseReader = new Scanner(conn.getInputStream());
            StringBuffer buffer = new StringBuffer();
            while (responseReader.hasNextLine()) {
               buffer.append(responseReader.nextLine()+"\n");
            }
            responseReader.close();
            //Printing the Response
            System.out.println(buffer.toString());
         }
      }else {
         System.out.println("Enter correct URL to process");
      }
   }
}

The output of the code:
Enter correct URL to process

READ  Class IllegalComponentStateException in Java

How to test a MalformedURLException?

The URL must start with predefined schemas(protocols). The Schemas are as follows:

  • ftp
  • http
  • https
  • gopher
  • mailto
  • news
  • NNTP
  • telnet
  • wais
  • file
  • Prospero

If we try to create a non-predefined protocol or schema, we will surely get an error.

The test case could be written in the below format:

@Test(expected=MalformedURLException.class)
public void checkURL() throws Exception{
URL myURL=new URL("htt://techtravelhub.com");
assertNotNull(myURL);
}

What are the packages use MalformedURLException?

MalformedURLException is used by the below packages:

PackageDescription
java.ioProvides for system input and output through data streams, serialization and the file system.
java.netProvides the classes for implementing networking applications.
java.rmiProvides the RMI package.
java.rmi.serverProvides classes and interfaces for supporting the server side of RMI.
javax.management.remoteInterfaces for remote access to JMX MBean servers.

 

    • Uses of MalformedURLException in java.io
Methods in java.io that throw MalformedURLException
Modifier and TypeMethod and Description
URLFile.toURL()

Deprecated.

This method does not automatically escape characters that are illegal in URLs. It is recommended that new code convert an abstract pathname into a URL by first converting it into a URI, via the toURI method, and then converting the URI into a URL via the URI.toURL method.

    • Uses of MalformedURLException in java.net
Methods in java.net that throw MalformedURLException
Modifier and TypeMethod and Description
URLURI.toURL()

Constructs a URL from this URI.

Constructors in java.net that throw MalformedURLException
Constructor and Description
JarURLConnection(URL url)

Creates the new JarURLConnection to the specified URL.

URL(String spec)

Creates a URL object from the String representation.

URL(String protocol, String host, int port, String file)

Creates a URL object from the specified protocol, host, port number, and file.

URL(String protocol, String host, int port, String file, URLStreamHandler handler)

Creates a URL object from the specified protocol, host, port number, file, and handler.

URL(String protocol, String host, String file)

Creates a URL from the specified protocol name, hostname, and file name.

URL(URL context, String spec)

Creates a URL by parsing the given spec within a specified context.

URL(URL context, String spec, URLStreamHandler handler)

Creates a URL by parsing the given spec with the specified handler within a specified context.

    • Uses of MalformedURLException in java.rmi
Methods in java.rmi that throw MalformedURLException
Modifier and TypeMethod and Description of
static voidNaming.bind(String name, Remote obj)

Binds the specified name to a remote object.

static String[]Naming.list(String name)

Returns an array of the names bound in the registry.

static RemoteNaming.lookup(String name)

Returns a reference, a stub, for the remote object associated with the specified name.

static voidNaming.rebind(String name, Remote obj)

Rebinds the specified name to a new remote object.

static voidNaming.unbind(String name)

Destroys the binding for the specified name that is associated with a remote object.

    • Uses of MalformedURLException in java.rmi.server
Methods in java.rmi.server that throw MalformedURLException
Modifier and TypeMethod and Description
static ClassLoaderRMIClassLoader.getClassLoader(String codebase)

Returns a class loader that loads classes from the given codebase URL path.

abstract ClassLoaderRMIClassLoaderSpi.getClassLoader(String codebase)

Provides the implementation for RMIClassLoader.getClassLoader(String).

static Class<?>RMIClassLoader.loadClass(String name)

Deprecated.

replaced by loadClass(String,String) method

Class<?>LoaderHandler.loadClass(String name)

Deprecated.

no replacement

static Class<?>RMIClassLoader.loadClass(String codebase, String name)

Loads a class from a codebase URL path.

static Class<?>RMIClassLoader.loadClass(String codebase, String name, ClassLoader defaultLoader)

Loads a class from a codebase URL path, optionally using the supplied loader.

abstract Class<?>RMIClassLoaderSpi.loadClass(String codebase, String name, ClassLoader defaultLoader)

Provides the implementation for RMIClassLoader.loadClass(URL,String), RMIClassLoader.loadClass(String,String), and RMIClassLoader.loadClass(String,String,ClassLoader).

static Class<?>RMIClassLoader.loadClass(URL codebase, String name)

Loads a class from a codebase URL.

Class<?>LoaderHandler.loadClass(URL codebase, String name)

Deprecated.

no replacement

static Class<?>RMIClassLoader.loadProxyClass(String codebase, String[] interfaces, ClassLoader defaultLoader)

Loads a dynamic proxy class that implements a set of interfaces with the given names from a codebase URL path.

abstract Class<?>RMIClassLoaderSpi.loadProxyClass(String codebase, String[] interfaces, ClassLoader defaultLoader)

Provides the implementation for RMIClassLoader.loadProxyClass(String,String[],ClassLoader).

    • Uses of MalformedURLException in javax.management.remote
Constructors in javax.management.remote that throw MalformedURLException
Constructor and Description
JMXServiceURL(String serviceURL)

Constructs a JMXServiceURL by parsing a Service URL string.

JMXServiceURL(String protocol, String host, int port)

Constructs a JMXServiceURL with the given protocol, host, and port.

JMXServiceURL(String protocol, String host, int port, String urlPath)

Constructs a JMXServiceURL with the given parts.

 

Best Practice on How to Handle MalformedException in our code

Handling other Exceptions with MalformedURLException is very important while working with the internet. The application may throw several exceptions along with the MalformedURLException. The generic try-catch block is a good starting point. But the best practice is to catch every exception.

Like java.net mat throw MalformedURLException and SecurityException.

So if we use a generic try-catch bock, it will produce very less information and will be tough to debug.

Secondly, we must not use multi-catch statements if they use an inheritance relationship.

Ref: Oracle doc

Share and Enjoy !

Leave a Comment

Your email address will not be published. Required fields are marked *