Switch to full style
Java2 codes,problems ,discussions and solutions are here
Post a reply

Creating your own Exceptions in Java

Sun Oct 12, 2008 7:21 am

Java defines several built-in classes for exception handling. All these classes are a part of the java.lang package which is automatically imported. That is why, while throwing an exception you did not specifically include any package for exception classes.

Apart from the built-in exception classes you can define your own exception classes. This is very useful when you want to define exception types which are having a behavior different from the standard exception type, particularly when you want to do validations in your application. The example given below created and used in the same, lava file, but it is possible to create and store exception type in packages and use them elsewhere.

Code:
class NumberRangeException extends Exception
{     
String msg;   
  NumberRangeException()   
{       
  msg = new String("Enter a number between 20 and 100");   
  }
}
public class My_Exception
{   
  public static void main (String args [ ])   
{         try 
       {   
          int x = 10;       
     if (x < 20 || x >100) throw new NumberRangeException( );
        }   
      catch (NumberRangeException e)       
  {   
          System.out.println (e);       
}
    }
}



the output of the code :
Code:
NumberRangeException


The exception class here is the NumberRangeException class. You must have noticed that this class is derived from the exception class. A variable 'msg' of String type is defined and in the constructor it is initialized with appropriate message. You are also overriding the function toString with statement 'System.out.println (e);' so that the caught exception object can convey some message when used in a print statement.



Post a reply
  Related Posts  to : Creating your own Exceptions in Java
 How to throw Exceptions in Java?     -  
 creating arrays in java     -  
 Creating a JAR file in Java     -  
 Creating a Java Application Build using RAD 7     -  
 creating application for Samsung using java     -  
 What are exceptions and how to handle them!!!     -  
 exceptions catch by a catch clause     -  
 Creating a Method in jsp     -  
 Creating a Directory in php     -  
 Creating table using div tag     -  

Topic Tags

Java Exceptions