top of page
Writer's pictureRajpreet Gill

Explore ATM and Exception Handling in java


Java is a programming language and a platform. Java is a high level, robust, object-oriented and secure programming language. Java is an object-oriented, class-based, concurrent, secured and general-purpose computer-programming language. It is a widely used robust technology. if i think what we can do with java, we can make so many Web Application, Desktop GUI and many more as you guys can see below. so, i thought to make a ATM(Automated teller machine) concept . Java is a Collection of Mind map like:

OOPs, Collection, data structure, MISC etcetera.




First of all, to make ATM We should have JAVA installed in local System as well as JDK version.


ATM program Java:


In Java, we can create an ATM program for representing ATM transection. In the ATM program, the user has to select an option from the options displayed on the screen. The options are related to withdraw the money, deposit the money, check the balance, and exit.

To withdraw the money, we simply get the withdrawal amount from the user and remove that amount from the total balance and print the successful message.

To deposit the money, we simply get the deposit amount from the user, add it to the total balance and print the successful message.

To check balance, we simply print the total balance of the user.

We use the exit(0) method to exit from the current Transaction mode and return the user to the home page or initial screen.



  1. //import required classes and packages   

  2. import java.util.Scanner;  

  3.   

  4. //create ATMExample class to implement the ATM functionality  

  5. public class ATMExample  

  6. {  

  7.     //main method starts   

  8.     public static void main(String args[] )  

  9.     {  

  10.         //declare and initialize balance, withdraw, and deposit  

  11.         int balance = 100000, withdraw, deposit;  

  12.           

  13.         //create scanner class object to get choice of user  

  14.         Scanner sc = new Scanner(System.in);  

  15.           

  16.         while(true)  

  17.         {  

  18.             System.out.println("Automated Teller Machine");  

  19.             System.out.println("Choose 1 for Withdraw");  

  20.             System.out.println("Choose 2 for Deposit");  

  21.             System.out.println("Choose 3 for Check Balance");  

  22.             System.out.println("Choose 4 for EXIT");  

  23.             System.out.print("Choose the operation you want to perform:");  

  24.               

  25.             //get choice from user  

  26.             int choice = sc.nextInt();  

  27.             switch(choice)  

  28.             {  

  29.                 case 1:  

  30.         System.out.print("Enter money to be withdrawn:");  

  31.                       

  32.         //get the withdrawl money from user  

  33.         withdraw = sc.nextInt();  

  34.                       

  35.         //check whether the balance is greater than or equal to the withdrawal amount  

  36.         if(balance >= withdraw)  

  37.         {  

  38.             //remove the withdrawl amount from the total balance  

  39.             balance = balance - withdraw;  

  40.             System.out.println("Please collect your money");  

  41.         }  

  42.         else  

  43.         {  

  44.             //show custom error message   

  45.             System.out.println("Insufficient Balance");  

  46.         }  

  47.         System.out.println("");  

  48.         break;  

  49.    

  50.                 case 2:  

  51.                       

  52.         System.out.print("Enter money to be deposited:");  

  53.                       

  54.         //get deposite amount from te user  

  55.         deposit = sc.nextInt();  

  56.                       

  57.         //add the deposit amount to the total balanace  

  58.         balance = balance + deposit;  

  59.         System.out.println("Your Money has been successfully depsited");  

  60.         System.out.println("");  

  61.         break;  

  62.    

  63.                 case 3:  

  64.         //displaying the total balance of the user  

  65.         System.out.println("Balance : "+balance);  

  66.         System.out.println("");  

  67.         break;  

  68.    

  69.                 case 4:  

  70.         //exit from the menu  

  71.         System.exit(0);  

  72.             }  

  73.         }  

  74.     }  

  75. }  



Output:

The Output will be like that....





Let's Move further to Exception Handling:



The Exceptional Handling in java is one of the powerful mechanism to handle the runtime errors so that the normal flow of the application can be maintained.




Exception is abnormal condition .

IN java, an exception is an event that disrupts the normal flow of the program.


Exception Handling: Exception handling is the mechanism to handle runtime errors such as ClassNotFoundException, IO Exception, SQLException, RemoteException, etc.


Advantage of Exception Handling:

  • The core advantage of Exception handling is to maintain the normal flow of the application.

  • An Exception normally disrupts the normal flow of the application that is why we use Exception Handling.



Let's see the scenario:



  1. statement 1;  

  2. statement 2;  

  3. statement 3;  

  4. statement 4;  

  5. statement 5;//exception occurs  

  6. statement 6;  

  7. statement 7;  

  8. statement 8;  

  9. statement 9;  

  10. statement 10;  


Suppose there are 10 statements in a Java program and an exception occurs at statement 5; the rest of the code will not be executed, i.e., statements 6 to 10 will not be executed. However, when we perform exception handling, the rest of the statements will be executed. That is why we use exception handling in Java.



Hierarchy of Java Exception classes:

The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by two subclasses: Exception and Error. The hierarchy of Java Exception classes is given below:





Apart From that,









Last but not least is Error, our third java Exception.


Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError, AssertionError etc.


Moreover, we have 5 java Exception Keywords.



Java Exception Handling Example:


1. TRY and CATCH:

The try statement allows you to define a block of code to be tested for errors while it is being executed.

The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.

The try and catch keywords come in pairs:

Let's see an example of Java Exception Handling in which we are using a try-catch statement to handle the exception.


  1. public class JavaExceptionExample{  

  2.   public static void main(String args[]){  

  3.    try{  

  4.       //code that may raise exception  

  5.       int data=100/0;  

  6.    }catch(ArithmeticException e){System.out.println(e);}  

  7.    //rest code of the program   

  8.    System.out.println("rest of the code...");  

  9.   }  

  10. }  


Output will be like that

Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...

Common Scenarios of Java Exceptions

There are given some scenarios where unchecked exceptions may occur. They are as follows:

1) A scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.

  1. int a=50/0;//ArithmeticException 

2) A scenario where NullPointerException occurs

If we have a null value in any variable, performing any operation on the variable throws a NullPointerException.

  1. String s=null;  

  2. System.out.println(s.length());//NullPointerException  

3) A scenario where NumberFormatException occurs

If the formatting of any variable or number is mismatched, it may result into NumberFormatException. Suppose we have a string variable that has characters; converting this variable into digit will cause NumberFormatException.

  1. String s="abc";  

  2. int i=Integer.parseInt(s);//NumberFormatException  

4) A scenario where ArrayIndexOutOfBoundsException occurs

When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may be other reasons to occur ArrayIndexOutOfBoundsException. Consider the following statements.

  1. int a[]=new int[5];  

  2. a[10]=50//ArrayIndexOutOfBoundsException  


2. Finally:

The finally statement lets you execute code, after try...catch, regardless of the result:

Example

public class Main {
  public static void main(String[] args) {
    try {
      int[] myNumbers = {1, 2, 3};
      System.out.println(myNumbers[10]);
    } catch (Exception e) {
      System.out.println("Something went wrong.");
    } finally {
      System.out.println("The 'try catch' is finished.");
    }
  }
}

The output will be:

Something went wrong.


The 'try catch' is finished.



3. The throw keyword:


The throw statement allows you to create a custom error.

The throw statement is used together with an exception type.

All methods use the throw statement to throw an exception. The throw statement requires a single argument: a throwable object. Throwable objects are instances of any subclass of the Throwable class. Here's an example of a throw statement.

throw someThrowableObject;

Example

Throw an exception if age is below 18 (print "Access denied"). If age is 18 or older, print "Access granted":

public class Main {
  static void checkAge(int age) {
    if (age < 18) {
      throw new ArithmeticException("Access denied - You must be at least 18 years old.");
    }
    else {
      System.out.println("Access granted - You are old enough!");
    }
  }

  public static void main(String[] args) {
    checkAge(15); // Set age to 15 (which is below 18...)
}
}
he output will be:

Exception in thread "main" java.lang.ArithmeticException: Access denied - You must be at least 18 years old.
        at Main.checkAge(Main.java:4)
        at Main. Main(Main.java:12)


I hope You guys enjoy this tutorial.....

Thanks for Reading...


References:

148 views

Recent Posts

See All
bottom of page