Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Java (http://www.go4expert.com/articles/java-tutorials/)
-   -   Creating your own Exceptions in Java (http://www.go4expert.com/articles/creating-exceptions-java-t4169/)

Sanskruti 6May2007 15:27

Creating your own Exceptions in Java
 
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: Java

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);
        }
    }
}

Output of the code is:

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.


All times are GMT +5.5. The time now is 14:34.