当前位置: 代码迷 >> java >> Java-如何在匿名类之外引发异常
  详细解决方案

Java-如何在匿名类之外引发异常

热度:102   发布时间:2023-08-02 10:46:24.0
try
{
    if(ruleName.equalsIgnoreCase("RuleName"))
    {
        cu.accept(new ASTVisitor()
        {
            public boolean visit(MethodInvocation e)
            {
                if(rule.getConditions().verify(e, env, parentKeys, astParser, file, cu)) // throws ParseException
                    matches.add(getLinesPosition(cu, e));
                return true;
            }
        });
    }
    // ...
}
catch(ParseException e)
{
    throw AnotherException();
}
// ...

我需要在底部catch中捕获引发的异常,但是我无法通过throws结构重载方法。 怎么办,请指教? 谢谢

创建自定义异常,在匿名类中编写try catch块,然后将其捕获到您的catch块中。

class CustomException extends Exception
{
      //Parameterless Constructor
      public CustomException () {}

      //Constructor that accepts a message
      public CustomException (String message)
      {
         super(message);
      }
 }

现在

try
{
    if(ruleName.equalsIgnoreCase("RuleName"))
    {
        cu.accept(new ASTVisitor()
        {
           try {

            public boolean visit(MethodInvocation e)
            {
                if(rule.getConditions().verify(e, env, parentKeys, astParser, file, cu)) // throws ParseException
                    matches.add(getLinesPosition(cu, e));
                return true;
            }

          catch(Exception e){ 
              throw new CustomException(); 
          }
        });
    }
    // ...
}
catch(CustomException e)
{
    throw AnotherException();
}

如已经建议的那样,可以使用未经检查的异常。 另一种选择是突变最终变量。 例如:

final AtomicReference<Exception> exceptionRef = new AtomicReference<>();

SomeInterface anonymous = new SomeInterface() {
    public void doStuff() {
       try {
          doSomethingExceptional();
       } catch (Exception e) {
          exceptionRef.set(e);
       }
    }
};

anonymous.doStuff();

if (exceptionRef.get() != null) {
   throw exceptionRef.get();
}
  相关解决方案