Sunday 20 June 2021

User Defined Exception in JAVA

Although Java’s built-in exceptions handle most common errors, you will probably want

to create your own exception types to handle situations specific to your applications. This

is quite easy to do: just define a subclass of Exception (which is, of course, a subclass of

Throwable). Your subclasses don’t need to actually implement anything—it is their existence

in the type system that allows you to use them as exceptions.

The Exception class does not define any methods of its own. It does, of course, inherit

those methods provided by Throwable. Thus, all exceptions, including those that you create,

have the methods defined by Throwable available to them.Exception defines four constructors. Two were added by JDK 1.4 to support chained

exceptions, described in the next section. The other two are shown here:

Exception( )

Exception(String msg)

The first form creates an exception that has no description. The second form lets you specify

a description of the exception.

Although specifying a description when an exception is created is often useful, sometimes

it is better to override toString( ). Here’s why: The version of toString( ) defined by Throwable

(and inherited by Exception) first displays the name of the exception followed by a colon, which

is then followed by your description. By overriding toString( ), you can prevent the exception

name and colon from being displayed. This makes for a cleaner output, which is desirable in

some cases.


 //User defined exception when radius of circle is negative

class MyException extends Exception

{

MyException()

{

//Empty Constructor must be there

}

MyException(String str)

{

super(str);

}

}

class DemoException

{

static double area(double r) throws MyException

{

if(r<0)

throw new MyException("Radius cannot be negative");

return 3.14*r*r;

}

public static void main(String args[])

{

try

{

System.out.println("Area is "+area(-10.0));

}

catch(MyException e)

{

//e.printStackTrace();

                        System.out.println(e.getMessage());//It will print Radius cannot be negative 

}

finally

{

System.out.println("Inside Finally");

}

System.out.println("Program Ends");

}

}

No comments:

Post a Comment