【问题标题】:How do I get a specific error message for a thrown exception in Java?如何获取 Java 中抛出的异常的特定错误消息?
【发布时间】:2014-04-17 17:57:57
【问题描述】:

我正在尝试获取两条不同的错误消息。显示一个:“X 坐标超出范围”,另一个显示“请输入一个数字”。这就是我认为你会编写代码的方式,但是,当然,它不起作用。

int x = -1;
int y = 0;

while(x < 0 || y < 0)
{
   try
   {
      System.out.println("X-Coordinate: ");
      x = kb.nextInt();
      if (x < 0)
      {
         throw new Exception("X-Coordinate out of bounds"); // desired message
      }
      System.out.println("Y-Coordinate: ");
      y = kb.nextInt();
      if (y < 0)
      {
         throw new Exception("Y-Coordinate out of bounds"); // desired message
      }
   }
   catch(Exception e)
   {
      // Desired default for other input errors
      System.out.println("Please enter a number"); 
      kb.nextLine();
   }
}

【问题讨论】:

    标签: validation exception try-catch message throw


    【解决方案1】:

    使用getMessage() 方法获取catch 块中的消息:

    try{
        throw new Exception("LOL I HAVE ERROR");
    }catch(Exception e){
        System.out.println("My error message: " + e.getMessage());
    }
    

    【讨论】:

      猜你喜欢
      • 2020-04-06
      • 1970-01-01
      • 2012-02-11
      • 2011-07-16
      • 1970-01-01
      • 2010-12-01
      • 2011-05-26
      • 1970-01-01
      • 2019-02-22
      相关资源
      最近更新 更多