0

I have the following method defined in one of my classes:

public String calculateProfitMargin() {
      String returnMe = "";
      double profitMargin = 0;
      try {
         profitMargin = (orderItems[0].getItem().getPriceSoldFor() - orderItems[0].getItem().getCostToCompany()) / ( (int) orderItems[0].getItem().getCostToCompany() );
      }
      catch (ArithmeticException e) {
         System.out.println("\nEXCEPTION CAUGHT\n________________");
         System.out.println("Details: / by Zero");
         System.out.println("To prevent this problem in the future DO NOT enter 0 as the cost to the company for any product in the system");
         System.exit(0);
      }
      returnMe = "The profit margin for Order " + orderNumber + " is: " + (profitMargin * 100) + "%";
      return returnMe;
   }

Later on in my program I use user input to set the values for priceSoldFor and costToCompany. Althought I set costToCompany to 0, the exception never took place. How do I fix this?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 1
    You will only get the ArithmeticException with int division. I guess you are doing double/float division, despite trying to cast the denominator to int, because the numerator is still a double/float. – Andy Turner Aug 12 '21 at 19:10
  • @AndyTurner Are there predefined exceptions for double/float division, and if so where can I find them, or would I have to define my own exception for something like this? – Pranay Doshi Aug 12 '21 at 19:13
  • 1
    If I had to write this method, I think I wouldn't catch an `ArithmeticException`, but rather just check if the denominator is nonzero. – MC Emperor Aug 12 '21 at 19:20
  • Previous [discussion](https://stackoverflow.com/questions/14137989/java-division-by-zero-doesnt-throw-an-arithmeticexception-why) on this topic. – RaffleBuffle Aug 12 '21 at 19:24

0 Answers0