Throwing User Defined Exception In Java


This Simple Java Program is for User Defined Exception in Java. This is a part of Mumbai University MCA Colleges Java Practicals. 

Exceptions are used to handle any abnormalities with in the program execution. The Main purpose or use of exception handling is to give the user the feel that the program terminated bug free. Exception handling avoids the abnormal termination of program.

In the Below program we create a class named MyException which Extends the Class Exception. Hence we need to import the Class Exception. The user defined MyException class calls the constructor of Exception class. In class C_area, a function calculates the area of the circle. The function throws a exception if the radius of the circle in entered negative. Which in turns calls the Exception class.




import java.lang.Exception;
class MyException extends Exception
{
MyException(String msg)
{
super(msg);
}
}

class C_area
{
double r,a;
C_area()
{
r=0;
a=0;
}
void calc_area(double r1)
{
try
{
r=r1;
if(r<0)
throw new MyException("Radius cannot be negative"); // User Defined Exception thrown
else
{
a= 3.14*r*r;
System.out.println("The area of circle is : "+ a);
}
}
catch(MyException e)
{
System.out.println("MyException triggered");
System.out.println(e.getMessage());
}
}
}

class Area
{
public static void main(String ar[])
{
C_area cir=new C_area();
cir.calc_area(-5); //Will Throw Exception
}
}


Output:-
MyException triggered
Radius cannot be negative


Hope this Java Program is useful to you in some sense or other. Keep following this blog for more Mumbai University MCA College Programs and simple Programs. Happy Programming and Studying

No comments:

Post a Comment