简体   繁体   English

尝试 - 捕获异常问题

[英]Try - Catch Exception issue

I'm trying to make a desktop calculator with different options (Hex, Binary, Octal, Decimal) and if a value is entered that is not of that mode, an error will appear saying, for example "BinaryInteger expected, the user entered 909382" and prompt again.我正在尝试制作具有不同选项(十六进制、二进制、八进制、十进制)的桌面计算器,如果输入的值不属于该模式,则会出现错误,例如“预期为 BinaryInteger,用户输入 909382 "并再次提示。 Right now the only error that appears is "Invalid option" due to my catch(Exception e).由于我的捕获(异常 e),现在出现的唯一错误是“无效选项”。 How do I write 4 exceptions/errors for invalid inputs.如何为无效输入编写 4 个异常/错误。

import java.util.*;

public class IntDriver
{
   //declared fields
   private static LongInteger num1;
   private static LongInteger num2;
   private static String opr;
   private static int mode = 0;
   // Operators that will be used
   private final static String[] Operators = { "", "+", "-", "*", "/" };

   public static void main(String[] args)
   {
      Scanner kb = new Scanner(System.in);

      boolean run = true;
      while(run)
      {
         displayMenu();

         while(true)
         {
            try
            {
               System.out.print("Option or value --> ");
               String option = kb.nextLine();

               switch(option.toLowerCase())
               {
               //modes

                  // decimal mode
                  case "decimal":
                  case "dcm":
                  case "dec":
                     mode = 0;
                     break;

                  // binary mode
                  case "binary":
                  case "bin":
                     mode = 1;
                     break;

                  //octal mode
                  case "octal":
                  case "oct":
                     mode = 2;
                     break;

                  //hex mode
                  case "hexadecimal":
                  case "hex":
                     mode = 3;
                     break;

                  //quit
                  case "q":
                  case "quit":
                     System.out.println("Thank you. Have a nice day.");
                     run = false;
                     break;

               //Operators
                  //add
                  case "+":
                     opr = "+";
                     break;

                  //subtract   
                  case "-":
                     opr = "-";
                     break;

                  //multiply   
                  case "*":
                     opr = "*";
                     break;

                  //divide
                  case "/":
                     opr = "/";
                     break;

                  //equals
                  case "=":
                     operate();
                     break;

                  default:
                     LongInteger temp;
                     //with mode it's in:
                     switch (mode)
                     {
                        case 1:
                           temp = new BinaryInteger(option);
                           break;
                        case 2:
                           temp = new OctalInteger(option);
                           break;
                        case 3:
                           temp = new HexInteger(option);
                           break;
                        default:
                           temp = new DecInteger(option);
                           break;
                     }
                     // if no num1 = LongInteger temp.
                     if (num1 == null)
                     {
                        num1 = temp;
                     }
                     else
                     {
                        if (opr == null)
                        {
                           throw new UnsupportedOperationException();
                        }
                        num2 = temp;
                     }

                     break;
               }
               break;
            }
            catch (UnsupportedOperationException e)
            {
               System.out.println("Invalid option; operator not specified.\n");
            }
            // Invalid option entered.
            catch (Exception e)
            {
               System.out.println("Invalid option.\n");
            }
         }
      }
   }
   //Menu Display
   private static void displayMenu()
   {
      System.out.println();

      switch (mode)
      {
         case 1:
            System.out.println("Binary Mode");
            break;
         case 2:
            System.out.println("Octal Mode");
            break;
         case 3:
            System.out.println("Hexadecimal Mode");
            break;
         default:
            System.out.println("Decimal Mode");
            break;
      }

      if (num1 != null)
      {
         System.out.print(num1 + "\t");
      }

      if (opr != null)
      {
         System.out.print(opr + "\t");
      }

      if (num2 != null)
      {
         System.out.print(num2 + "\n");
      }
      System.out.println("\n\n\tModes:\t\t    Operators:");
      System.out.println("\tBin - Binary\t\t+");
      System.out.println("\tOct - Octal\t\t-");
      System.out.println("\tDcm - Decimal\t\t*");
      System.out.println("\tHex - Hexadecimal\t/");
      System.out.println("\tQ   - Quit\t\t=\n");
   }

   private static void operate() throws Exception
   {

      if (num1 == null || num2 == null || opr == null)
      {
         throw new Exception("Not enough numbers.");
      }

      switch (opr)
      {
         case "+":
            num1 = num1.calcValue(opr, num2, mode);
            break;
         case "-":
            num1 = num1.calcValue(opr, num2, mode);
            break;
         case "*":
            num1 = num1.calcValue(opr, num2, mode);
            break;
         case "/":
            num1 = num1.calcValue(opr, num2, mode);
            break;
         default:
            throw new Exception("Invalid operator.");
      }

      num2 = null;
      opr = "";
   }


}

You could go and extend java.lang.Exception 4 times for each case :您可以为每种情况扩展java.lang.Exception 4 次:

public class YourCustomException extends Exception {

  //copy paste and modify whatever constructors are relevant in your case.

}

.. and then go on and throw those 4 exceptions when you have invalid input for your modes. .. 然后当您的模式输入无效时继续抛出这 4 个异常。 This is rather inefficient in your case, though.但是,这在您的情况下效率很低。 I think your case is simple enough that you can simply do something like:我认为您的案例很简单,您可以简单地执行以下操作:

public class DecInteger {

    public DecInteger (String option)
    {
        if (isNotDecimal(option))
            throw new Exception("Input option " + option + " is not a decimal");
    }

}

.. then in your catch block you will need to do something like this: ..然后在你的catch块中你需要做这样的事情:

catch(Exception ex) {
    System.out.println(ex.getMessage);
}

Technically speaking it is not good practice to throw exceptions of type Exception , it is better to create subtypes that are more descriptive to the actual exception, but your case is simple enough where this doesn't really matter.从技术上讲,抛出Exception类型的Exception不是一个好习惯,最好创建对实际异常更具描述性的子类型,但是您的情况很简单,这并不重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM