Built-in exception and User-defined exception

Built-in exception

Built-in exception are the exceptions which are already in java. These exceptions are suitable to explain certain error situations.

Exception class Meaning
ArithmeticException Thrown when an exception condition has occurred in an arithmetic operation.
ArrayIndexOutOfBoundsException Thrown to indicate that an array has been accessed eith an illegal index.
ClassNotFoundException Raised when we try to access a class whose defination is not found.
FileNotFoundException Raised when a file is not accessible or does not open.
IOException Thrown when an input output operation failed or interrupted.
InterruptedException Thrown when a thread is waiting, sleeping or doing some processing and it is interrupted.
NoSuchFieldException Thrown when a class does not contain the field or specified.
NoSuchMethodException Thrown when accessing a method which is not found.
NullPointerException  Raised when referring to the members of a null object, null represent nothing.
NumberFormatException Raised when a method could not convert a string into a numeric format.
RuntimeException This represents any exception which occurs during runtime.
StringIndexOutOfBoundsException  Thrown by string class methods to indicate that an index is either negative or greater than the size of the string.

User-defined exception

  • In many cases, a user program may have to validate certain i/p values or monitor for specific conditions & raise an exception if these conditions are violated. Hence, the user has to define its own exception
  • Just define a subclass of Exception
  • The Exception class does not define any methods of its own
  • It inherits those methods provided by Throwable
  • Thus, all exceptions, including those that you create, have the methods defined by Throwable available to them
Example
import java.io.IOException;
class test extends Exception
{
private static int accno[]={1,2,3,4,5};
private static String name[]={“Jonh”, “Adam”, “Chris”, “Faf”, “Steve”};
private static double bal[]={10000, 15000, 50000, 12000, 43000};
test()
{
}
test(String str)
{
super(str);
}
public static void main(String args[])
{
try
{
System.out.println(“ACCNO”+”\t”+”CUSTOMER”+”\t”+”BALANCE”);
for(int i=0;i<5;i++)
{
System.out.println(accno[i]+”\t”+name[i]+”\t”+bal[i]);
if(bal[i]<1000)
{
test t = new test(“Balance is less”);
throw t;
}
}
}
catch(test t)
{
t.printStackTrace();
}
}
}

Output:
ACCNO CUSTOMER BALANCE
1 Jonh 10000.0
2 Adam 15000.0
3 Chris 50000.0
4 Faf 12000.0
5 Steve 43000.0

Leave a Reply

Your email address will not be published. Required fields are marked *