In Java, it is possible to create own exceptions to
handle situations specific to an application.
In Java, it is done by defining a subclass of Exception(which is a subclass of Throwable).
The Exception class does not define any method of
its own; it inherits those methods provided by Throwable.
The methods prov
ided by Throwable are:
ided by Throwable are:
Example:
class Exception1 extends Exception
{
privateintval;
Exception1(int s)
{
val=s;
}
public String toString()
{
return "Exception Occurred [
"+val+" ] is not allowed";
}
}
class Check
{
public void generate(intnum) throws
Exception1
{
System.out.println("Inside the
function");
if(num<0)
throw new Exception1(num);
System.out.println("Normal
Finish");
}
}
classMyexception
{
public static void main(String args[])
{
try
{
Check t=new Check();
t.generate(10);
t.generate(-10);
}
catch(Exception1 e)
{
System.out.println("Exception
occurred inside main:\n"+e);
}
}
}
Output:
Inside the function
Normal Finish
Inside the function
Exception occurred inside main:
Exception Occurred [ -10 ] is not allowed
No comments:
Write comments