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

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact