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 BYE
OUTPUT 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)

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.