Dividing a Number in Java with Exception Handling

Description:

In this java code, we show you how to handle Exceptions when you divide two numbers by each other.

Code:

package com.javaproblems.divisionbyzerowithe;

import java.util.InputMismatchException;
import java.util.Scanner;

public class DivisionByZeroE {

 private static int ratio(int num, int denom) {
  return num/denom;
 }

public static void main(String[] args) {
 int numerator, denominator, result;
 @SuppressWarnings("resource")
Scanner scan = new Scanner(System.in);
 boolean continueLoop = true;
 do {
  try { 
  System.out.println("Please enter numerator: ");
  numerator = scan.nextInt();
  System.out.println("Please enter denominator: ");
  denominator = scan.nextInt();
    
  result = ratio(numerator, denominator);
  System.out.println(result);
  continueLoop = false;
  }
                catch(InputMismatchException e) {
    System.out.println("Exception: " + e);
    scan.nextLine();
  System.out.println("You must enter an int value."
                                    + " Please try again");
   } catch (ArithmeticException e) {
   System.out.println("Exception: " + e.getMessage());
   System.out.println("Zero is not a valid value. + " +
      " Please try again");
   }
   
   
  } while(continueLoop);
  
  
 }
}
 

No comments:

Post a Comment