Program to accept a password from the user and throw 'Authentication Failure' exception if the password is incorrect
In this program, we have to throw an exception if user enters wrong password. The IOException signals that an I/O exception of some sort has occurred. This class is the general class of exceptions produced by failed or interrupted I/O operations.
The printStackTrace( ) method of Throwable class which prints throwable and its backtrace to the standard error stream.
PROGRAM
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class AuthenticationException extends Exception {
public AuthenticationException(String message) {
super(message);
}
}
public class AuthenticationExcDemo {
public static void main(String[] args) {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String pwd;
try {
System.out.print("Enter password :: ");
pwd = br.readLine();
if(!pwd.equals("123"))
throw new AuthenticationException("Incorrect password\nType correct password");
else
System.out.println("Welcome User !!!");
}
catch (IOException e) {
e.printStackTrace();
}
catch (AuthenticationException a) {
a.printStackTrace();
}
System.out.println("BYE BYE");
}
}
OUTPUT 1
C:\>javac AuthenticationExcDemo.java C:\>java AuthenticationExcDemo Enter password :: 123 Welcome User !!! BYE BYEOUTPUT 2
C:\javac AuthenticationExcDemo.java C:\java AuthenticationExcDemo Enter password :: abc exception.AuthenticationException: Incorrect password Type correct passwordBYE BYE at exception.AuthenticationExcDemo.main(AuthenticationExcDemo.java:34)
What is the name of your Java Source file and Java Class?
ReplyDeleteHere, the file name is "AuthenticationExcDemo.java" and class name "AuthenticationExcDemo".