Q) Example program an user defined exception implementation?
A)
class votingException extends Exception
{
}//user defined, checked Exception
class voting
{
public static void isEligibletovote(int age) throws votingException
{
if (age<19)
throw new votingException();
System.out.println("can cast vote");
}
}
class votingapplication {
public static void main(String[] args) {
try
{
int age=Integer.parseInt(args[0]);
voting.isEligibletovote(age);
}
catch(Exception e)
{
System.out.println(e);
if(e instanceof votingException)
System.out.println("invalidage. can't vote");
if( e instanceofNumberFormatException)
System.out.println("please supply again digits only");
}
/*only one catch block. It is not advisable because more no.of conditions reduces the performance.*/
/*catch(votingException e)
{
e.printStackTrace();
System.out.println("invalid age. can't vote");
}
catch(NumberFromatException e)
{
System.out.pritnln(e.getMessage());
System.out.println("please supply age in digits only");
}*/
}
}
Output:
java.lang.ArrayIndexOutOfBoundsException: 0
java.lang.ArrayIndexOutOfBoundsException: 0
Note:
->Whenever multiple exceptions i.e. more than one kind of exception raising chance is there in try block, to handle each exception specifically, we go for multiple catch blocks.
->even though multiple catch blocks are implemented, only one catch block is executed.
->when we specify multiple catch blocks, super class executed catch blocks should not precedence the sub class exception catch block.
Unreadable code is a syntactical error in java”
Ex:
try
{ }
catch(Exception e)
{ }
catch(NumberFormateException e)
{ }
->Here syntactical exception is raised. The super class exception(i.e. Exception) is precedence to the its child class exception (i.e. NumberFormateException).
try
{ }
catch(NumberFormateException e)
{ }
catch (Exception e)
{ }
->Here error is not raised.
Additional information:
->getMe() it returns a string not location information.
It returns the error description but not returns where it is raised. i.e. line number (it is location information).
->1) type of exception
2) Error description
3) Location is also displayed with e.printStackTrace()
->when directly priting the exception reference i.e. when we display System.out.println(e);
Then it display:
Type of exception
Error description, but it not displays location of exception.
Comments
Post a Comment