SIGN UP MEMBER LOGIN:    
ARTICLE

Defining Your Own Exception Class in JAVA (Custom Exception)

Posted by Abhishek Dubey Articles | Java February 01, 2012
This article is helpful for making your own exception classes and and making your own exception condition.
Reader Level:

Defining your own Exception class in JAVA

Now you know how to write exception handlers for those exception objects that are thrown by the runtime system, and thrown by a method in the standard class library.

It is also possible for you to define your own exception classes and to cause objects of those classes to be thrown whenever an exception occur. In this case, you get to decide just what constitutes an exceptional condition. For example, suppose you could write a data-processing application that processes integer data obtained via a TCP/IP link from another computer. If the specification for the program indicates that the integer value 100 should never be received, then you could use an occurrence of the integer value 100 to cause an exception object of your own design to be thrown.


 exceptFig1.jpg.gif

Exception Types

Mainly Exceptions are of two types; checked and unchecked exceptions:
  • Error and Runtime Exception are unchecked these exception not handled or check by compiler that you  handle them explicitly
  • All other Exception are checked that is compiler enforce or check that you can handle them explicitly

An error is an abnormal situation of the JVM (Java Virtual Machine)

  • Running out of memory
  • Infinite recursion
  • Inability to link

Creating Custom Exceptions

  • Use the Exception class in the API.
  • Create a Custom Exception class if  the predefined class is not sufficient.
  • Declare a custom exception classes by extending the Exception class or  a subclass of Exception.
If you decide to define your own exception class. it must be a subclass of a Throwable class. You must decide which class you will extend.
The two existing subclasses of Throwable are Exception and Error.  

Example-1 
This example is making your own Exception class by using constructor. 


// this is a user define exception class etend by Exception class

class
Myexception extends Exception
     {
      public Myexception(int i)
        {
        System.out.println("you " +i +" entered It exceeding the limit");
        }

      }

public class ExceptionTest
    {
    public void show(int i) throws Myexception
          {
       if(i>100)
         throw new Myexception(i);
       else
         System.out.println(+i+" is less then 100 it is ok");
          }

   public static void main(String []args)
        {
        int i=Integer.parseInt(args[0]);
        int j=Integer.parseInt(args[1]);
        ExceptionTest t=new ExceptionTest();
            try{
                t.show(i);
                t.show(j);
                }
                catch(Throwable e)
                        {
                System.out.println("catched exception is"+e);
                        }
        }
}

OUTPUT

customexception cmd.gif

Example-2

This example is making your own Exception class by using super keyword.

class MyException extends Exception
    {
    MyException(String s)
     {
      super(s);
     }
    public String toString()
        {
           return(" " + getMessage());
        }
   }
class ThrowClass
  {
    int age;
     ThrowClass(int age)  throws MyException
       {
       this.age=age;
       }        
     void getAge(int age) throws MyException
      {
       if(age <18 )
        {
         throw new MyException("Invalid Age");
              }
        else
        {
         this.age=age;
        }
      }
   }
   class TestException
   {

    public static void main(String [] args)
     {
        int a=Integer.parseInt(args[0]);
       try
        {
          ThrowClass t=new ThrowClass(a);
            t.getAge(a);
       System.out.println(t.age);
        }
        catch(MyException me)
           {
          System.out.println(me);
              }
     }

   }

OUTPUT

testException.gif 

Resources

How to Handle a Custom Exception in C#Creating Your Own Exception Classes in C#Exception Handling in C#

Login to add your contents and source code to this article
share this article :
post comment
 
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Become a Sponsor