Custom Exception in Java

Advertisements

Prev Tutorial Multi Threading 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
custom exception

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

Download Code Click

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.


Prev Tutorial Multi Threading in Java

Advertisements

Buy This Ad Space @$20 per Month, Ad Size 600X200 Contact on: hitesh.xc@gmail.com or 9999595223

Pure VPN Privide Lowest Price VPN Just @ $1.65. Per Month with Non Detected IP Lowest Price Non Detected IP VPN

Magenet is best Adsense Alternative here we earn $2 for single link, Here we get links ads. Magenet

For Projects 9999595223

Google Advertisements


Buy Websites 9999595223

Buy College Projects with Documentation Contact on whatsapp 9999595223. Contact on: hitesh.xc@gmail.com or 9999595223 Try this Keyword C++ Programs

Advertisements