【问题标题】:How do I display an exception?如何显示异常?
【发布时间】:2013-11-04 12:00:11
【问题描述】:

我正在检查用户输入的号码是否是 Zeckendorf,如果不是,我想显示一个异常,我该怎么做?另外,如何将 Zeckondorf 转换为其十进制等效值?

import java.util.Scanner;


public class IZeckendorfNumberConvertor {
static String number;
int zeckonderEquivalent;
static Scanner scanner = new Scanner(System.in);

public static void main(String[] args) {

    convertToZeckonderNumber();
    isTrueZeckonderNumber();
}

private static boolean isTrueZeckonderNumber() {
    System.out.println("Enter a Zeckonder Number:");
    number = scanner.nextLine();
    if (number.equals("10100")) 
    {
        return true; } 
    else if (number.equals("010011") || number.equals("010100")) 
    { 
        return false; }
    return false;
}

private static void convertToZeckonderNumber() {

}}

【问题讨论】:

  • 您确定要例外,而不仅仅是反馈消息吗?
  • 是的异常,它必须抛出异常

标签: java exception converter


【解决方案1】:

我建议您不要显示异常(即跟踪等),因为它对用户非常不友好。 您可以使用 throw 语法来抛出适当的异常:

 throw new Exception("Given number is not a Zeckendorf number");

但一定要抓住它并显示一个漂亮而干净的消息:

try {
   // Your input code goes here
} catch (Exception e) {
    System.out.println(e.getMessage());
}

另一个更简单的选择是只检查方法的返回值并相应地打印结果。

我建议使用后一种解决方案,因为当您的程序中发生不良和意外情况并且您希望优雅地处理它时,会使用异常。在您的情况下,这种行为是预期的(即用户提供了错误的数字),因此检查返回值将更加干净和容易。

【讨论】:

  • 最后一段+1:在这种情况下使用布尔返回值更简洁。
【解决方案2】:

使用 try catch 块捕获异常

            try {

            } catch (Exception e) {

                e.printStackTrace();
            }

也可以使用 throw 来抛出一个新异常

【讨论】:

    【解决方案3】:

    假设确实想要显示异常,而不是更用户友好的消息,第一步可能是将异常作为字符串获取。然后你可以用那个字符串做你喜欢的事情(回显到控制台,放在 javax.swing.JTextArea 中,通过电子邮件发送等等)。

    如果您只是想要来自异常的消息,那么 getMessage() 会做:

    try { ... }
    catch(FooException e) {
        String msg = e.getMessage();
    }
    

    但是,如果你想要整个异常、堆栈跟踪和所有内容,你会想要这样的东西:

    public static String stackTrace(Exception e) {
        StringWriter w = new StringWriter();
        e.printStackTrace(new PrintWriter(w));
        return w.toString();
    }
    
    // ...
    
    try { ... }
    catch(FooException e) {
        String st = stackTrace(e);
    }
    

    如果您只想将完整的堆栈跟踪回显到控制台,可以使用 printStackTrace(),无参数方法:

    try { ... }
    catch(FooException e) {
        e.printStackTrace();
    }
    

    如果您想更好地控制堆栈跟踪的显示,您可以通过以下方式获取详细信息:

    try { ... }
    catch(FooException e) {
        StackTraceElement[] stes = e.getStackTrace();
        // Do something pretty with 'stes' here...
    }     
    

    【讨论】:

      【解决方案4】:

      您可以使用简单的if 向用户打印一条错误消息,说明输入错误。

      if(yourCondition){
          // Happy scenario
          // Go shead
      }else{
          // Error Scenario
          System.out.println("Error. Invalid Input.");
          // If you persist to throw an exception, then you can do something like this
          // throw new Exception("Exception Explanation"); // I've commented this, but you can uncomment it if needed
          // But the advice is to display an error message, than throw a exception.
      }
      

      关于转换,您可以像这样将二进制转换为十进制

      int i = Integer.parseInt(binaryString, 2); // 2 indicates the radix here, since you want to convert from binary.
      

      【讨论】:

        【解决方案5】:

        使用此代码 sn-p 您可以将字符串转换为整数:

        int numberAsInt;
            try {
                  numberAsInt = Integer.parseInt(number);
            } catch (NumberFormatException e) {
                  //Will throw an Exception
            }
        

        如果你想创建自己的异常类,你可以像 here 那样做,或者只是抛出一个 RuntimeException

        throw new RuntimeException("Your Message");
        

        【讨论】:

          【解决方案6】:

          我的意见,你可以试试像下面这样的

           public static void main(String[] args) {    
            if(!isTrueZeckonderNumber()){
                // your message should goes here
                 System.out.println("Your message");
              }
           }
          

          如果你真的想抛出异常,请执行以下操作

           private static boolean isTrueZeckonderNumber() throws Exception{
              System.out.println("Enter a Zeckonder Number:");
              number = scanner.nextLine();
              if (number.equals("10100")) {
                  return true;
              } else{
                  throw new Exception("your message");
              }        
          }
          

          【讨论】:

            【解决方案7】:

            你想显示异常是什么意思? 我建议只给用户反馈,因为异常更常用于不应该发生的异常操作。

            但是,如果您确实愿意,您可以打印一条消息来解释发生了什么。

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

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2013-05-15
              • 1970-01-01
              • 2011-09-01
              • 2020-04-11
              • 2011-10-05
              • 2013-07-31
              • 1970-01-01
              相关资源
              最近更新 更多