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.

Related Posts:

  • Applet in Java Applet is a predefined class in java.applet package used to design distributed application. It is a client side technology. Applets are run on web … Read More
  • Java Scanner Class in Java Scanner is one of the predefined class which is used for reading the data dynamically from the keyboard. Import Scanner class Syntax java.u… Read More
  • Socket Programming in Java Networking is a concept of connecting two or more computing devices together so that we can share resources like printer, scanner, memory. In… Read More
  • 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. R… Read More
  • Command Line Arguments in Java If any input value is passed through the command prompt at the time of running of the program is known as command line argument by defaul… Read More

0 comments:

Post a Comment