Creating your own Exceptions in Java

Discussion in 'Java' started by Sanskruti, May 6, 2007.

  1. Sanskruti

    Sanskruti New Member

    Jan 7, 2007
    Likes Received:
    Trophy Points:
    Software Consultant
    Mumbai, India
    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.

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

    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.

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice