Creating Your own Exceptions in Java

  • 0
     An exception is generally a run time error that leads to unwanted instant termination of the program. An exception must be handled, failing to do so leads to transfer of control of execution to Java's default exception handler. In this article, I would try to develop an exception which is generated if you use a special name "HERR".
Here is the program.
package ExceptionIllustration;

class NameException extends Exception
{
 private String name;
 
 NameException(String name)
 {
  this.name = name;
 }
 
 public String toString()
 {
  return ("You can't use the name " + name);
 }
}

class CustomExceptionDemo
{
 static void PrintName(String Name) throws NameException
 {
  if(Name.equals("Herr"))
  {
   throw new NameException("Herr");
  }
  else
   System.out.println("Entered Name is " + Name );
 }
 public static void main(String... args)
 {
  try
  {
   PrintName("Her");
   PrintName("Herr");
  }
  catch(NameException e)
  {
   System.out.println("Caught Exception " + e);
  }
 }
}
In the above program, new exception created is NameExcepion that occurs when user tries to use the name "Herr". The Method PrintName() deals with the necessary details, it checks whether the name provided is "Herr" or not. If it is, an new NameException is thrown, otherwise, simply a name is print. To compile the program
javac -d .CustomExceptionDemo.java
And to run the porogram
java ExceptionIllustration.CustomExceptionDemo
Here is the output that I received in my program.
Entered Name is Her
Caught Exception You can't use the name Herr

No comments:

Post a Comment