【问题标题】:Catch exceptions without a try block?在没有 try 块的情况下捕获异常?
【发布时间】:2014-04-12 03:08:09
【问题描述】:

我在代码中的特定情况下抛出了很多自定义异常,我希望在方法的底部有一个 catch 块来处理它们。

所有的异常都是 Exception 类 CribbageException 的子类,所以我想要:

public void myMethod(){
     if (whatever){
          throw new CardException();
     }
     if (something else){
         throw new InvalidCardException();
     }
     if (scenario 3){
          throw new TwoCardsException();
     }
     catch (CribbageException e) {
          System.out.println(e.getMessage());
     }
}

但是我得到了一个没有尝试错误的捕获。

有没有办法使用这种类型的异常处理?

【问题讨论】:

  • catch without try 大声说几遍。
  • 按照错误提示添加 try 块。

标签: java exception-handling try-catch


【解决方案1】:

将所有throws 包装在一个try 中。

public void myMethod(){
    try {
        if (whatever){
             throw new CardException();
        }
        if (something else){
            throw new InvalidCardException();
        }
        if (scenario 3){
            throw new TwoCardsException();
        }
    }
    catch (CribbageException e) {
          System.out.println(e.getMessage());
    }
}

【讨论】:

  • 是的,这是有道理的。谢谢。
猜你喜欢
  • 2011-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-19
  • 2019-07-12
  • 1970-01-01
  • 2016-10-12
  • 2016-06-26
相关资源
最近更新 更多