Advertisement
karlakmkj

Exception Handling

Sep 6th, 2020 (edited)
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.16 KB | None | 0 0
  1. package javaPack;
  2.  
  3. import java.util.InputMismatchException;
  4. import java.util.Scanner;
  5.  
  6. public class Exceptionhandling {
  7.  
  8.     public static void main(String[] args) {
  9.        
  10.         int number1 = 0, number2 = 0, result =0;
  11.         boolean isFlag = false;
  12.        
  13.         do {
  14.             try {
  15.                 Scanner input = new Scanner(System.in);
  16.                 System.out.println("Enter first integer no: ");
  17.                 number1 = input.nextInt();
  18.                 System.out.println("Enter second integer no: ");
  19.                 number2 = input.nextInt();
  20.                 result = number1/number2;
  21.                 System.out.println("Result: " + result);
  22.                 isFlag = true;
  23.                 input.close();
  24.             }
  25.             //All types of exception can be named as e in each catch
  26.             catch(InputMismatchException e) {
  27.                 System.out.println("Please enter valid number!");
  28.             }
  29.             catch(ArithmeticException e) {
  30.                 System.out.println("Second number cannot be zero!");
  31.             }
  32.             catch(Exception e) {
  33.                 System.out.println("An exception occurred");
  34.             }
  35.             finally {
  36.                 System.out.println("This statement is always excuted.");
  37.             }
  38.         } while(!isFlag); //Loop will keep going when exception occurs
  39.                     //until when correct output is shown then isFlag will become true  
  40.     }
  41. }
  42.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement