JPR Manual Answers Experiment 12
JPR Manual Answers Experiment 12
: 12
Program Statement 1: Demonstrate exception handling using try, catch and finally block.
Source Code:
try
{
int result=numbers[5];
System.out.println("Result:"+result);
int length=str.length();
System.out.println("Length:"+length);
int divisionResult=10/0;
System.out.println("Division Result:"+divisionResult);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Caught
ArrayIndexOutOfBoundException:"+e.getMessage());
}
catch(NullPointerException e)
{
System.out.println("Caught
NullPointerException:"+e.getMessage());
}
catch(ArithmeticException e)
{
System.out.println("Caught
ArithmeticException:"+e.getMessage());
}
finally
{
System.out.println("Finally block always executes.");
}
Program Statement 2: WAP to accept a password from the user and throw “Authentication
Failure” Exception if the password is incorrect.
Source Code:
import java.util.Scanner;
try
{
System.out.println("Enter password:");
String epass=s.nextLine();
if(!epass.equals(pass))
{
throw new AuthenticationFailureException("Incorrect
password");
}
System.out.println("Authentication successful.");
}
catch(AuthenticationFailureException e)
{
System.out.println("Authentication failed:"+e.getMessage());
}
}
}
Output: