Saturday

Custom Exception in Java


Custom Exception in Java
If any exception is design by the user known as user defined or Custom Exception. Custom Exception is created by user.
Rules to design user defined Exception
1.     Create a package with valid user defined name.
2.     Create any user defined class.
3.     Make that user defined class as derived class of Exception or RuntimeException class.
4.     Declare parametrized constructor with string variable.
5.     call super class constructor by passing string variable within the derived class constructor.
6.     Save the program with public class name.java

Example
// save by AgeException.java
package nage;

public class AgeException extends Exception
{
public AgeException(String s)
{
super(s);
}
}
Compile: javac -d . AgeException.java
Example
// save by CheckAge.java
package nage;

public class CheckAge
{
public void verify(int age)throws AgeException
{
if (age>0)
{
System.err.print("valid age");
}
else
{
AgeException ae=new AgeException("Invalid age");
throw(ae);
}
}
}
Compile: javac -d . CheckAge.java
Example
// save by VerifyAgeException

import nage.AgeException;
import nage.CheckAge;
import java.util.*;

public class VerifyAgeException
{
public static void main(String args[])
{
int a;
System.out.println("Enter your age");
Scanner s=new Scanner(System.in);
a=s.nextInt();
try
{
CheckAge ca=new CheckAge();
ca.verify(a);
}
catch(AgeException ae)
{
System.err.println("Age should not be -ve");
}
catch(Exception e)
{
System.err.println(e);
}
}
}
Compile: javac VerifyAgeException.java
custom exception

Steps to compile and run above program
First you save verify-age files into you PC in any where, here i will save this file in C:\>
·         C:\verify-age\>javac -d . AgeException.java
·         C:\verify-age\>javac -d . CheckAge.java
·         C:\verify-age\>javac VerifyAgeException.java
Note: First compile AgeException.java code then CheckAge.java and at last compile VerifyAgeException.java code.

0 comments:

Post a Comment