MalformedURLException Java

MalformedURLException Java

Summary: By the end you reach this tutorial you will understand the possibility of throwing MalformedURLException Java.

The JDK 1.5 includes twelve exceptions used with network programming. The commonly occurring are MalformedURLException and UnknownHostException. Let us when they are thrown in coding.

MalformedURLException is a checked exception. It is inherited from IOException. MalformedURLException is raised by JVM in two occasions.

1. The protocol given in the address as URL may not be a correct (valid) one for the job.
2. The address given in the URL constructor may not be evaluated successfully (due to wrong format etc) by the networking software.

Following is the class signature

public class MalformedURLException extends IOException

Following is the hierarchy.

Object –> Throwable –> Exception –> IOException –> MalformedURLException

Full hierarchy of exceptions is available at "Hierarchy of Exceptions – Checked/Unchecked Exceptions".

Two constructors are available (a common feature for most exceptions)

1. MalformedURLException(): Creates a MalformedURLException object that can be thrown or handled.
2. MalformedURLException(String message): Creates a MalformedURLException object and the message mentioned in the constructor is displayed to the user.

Observe the URL constructor signature

public URL(String) throws MalformedURLException

See, the constructor throws MalformedURLException.

Following program illustrates the usage
import java.net.*;
public class MUE
{
  public static void main(String args[])
  {
    try 
    {
      URL u1 = new URL("http://www.yahoo.com:80/index.jsp#chapter1");                                
      System.out.println("Protocol: " + u1.getProtocol());
    }
    catch (MalformedURLException e) 
    {
      System.err.println("Protocol name is wrong. " + e);
    }
  }
}

MalformedURLException Java
In the above program, instead of http give something wrong protocol like httppp, it raises exception. See the next screenshot.

import java.net.*;
public class MUE
{
   public static void main(String args[])
   {
     try 
     {
       URL u1 = new URL("httppp://www.yahoo.com:80/index.jsp#chapter1");                                
       System.out.println("Protocol: " + u1.getProtocol());
     }
     catch (MalformedURLException e) 
     {
       System.err.println("Protocol name is wrong. " + e);
     }
   }
}

MalformedURLException Java

Leave a Comment

Your email address will not be published.