Tuesday, 29 November 2016

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)

5 comments:

  1. Your program doesn't work it shows Error: Could not find or load main class AuthenticationExceptionDemo
    Caused by: java.lang.ClassNotFoundException: AuthenticationExceptionDemo
    help me out

    ReplyDelete
    Replies
    1. What is the name of your Java Source file and Java Class?

      Here, the file name is "AuthenticationExcDemo.java" and class name "AuthenticationExcDemo".

      Delete
  2. the source file name in java is where we write main method then that class name is given to that particular java programe

    ReplyDelete
  3. So luck to come across your excellent blog. Your blog brings me a great deal of fun.. Good luck with the site. digitogy.com

    ReplyDelete
  4. You guys are writing some Amazing tips. Thanks for sharing this. Totally Awesome Post Please Keep Posting Regularly.
    echobeat earbuds review, chargeboost reviews, liporing review , doc socks, livewave antenna review

    ReplyDelete