java - 处理异常的问题

标签 java exception

我已经创建了自己的异常,但是当我尝试使用它时,我收到一条消息,说它不能转换为我的异常

我有一个这样的界面

public interface MyInterface
{   
    public OtherClass generate(ClassTwo two, ClassThree three) throws RetryException;
}

其他类似的

public class MyGenerator{   
  public class generate (ClassTwo two, ClassThree three){
    try{
    }catch(MyException my)
  }
}

最后是另一个类中的方法

public Object evaluate(String expression, Map values) throws FirstException, RetryException
{
   try{
   }catch (Exception x){
     if(x instanceof FirstException){
       throw new FirstException()
     }
     else{
       RetryException retry= (RetryException)x;
       retry.expression = expression;
       retry.position = position;
       retry.operator = tokens[position];
       retry.operand = 1;
       throw retry; 
     }
  }
}

最后一个方法上的这个 try catch block 是进行数学运算,我想在 RetryException 上捕获被零除的异常。

最佳答案

RetryException retry= (RetryException)x; 

这行代码试图将异常转换为 RetryException。这仅在以下情况下有效: RetryException 适本地扩展了您正在捕获的异常类型(我认为 ArithmeticException 用于除以零?)。并且异常实际上是一个 RetryException。在不查看您的更多逻辑的情况下,我们不知道这是否属实。

尝试检查

if (x instanceof RetryException)

在你做这个 Actor 之前。您的代码可能会引发不同类型的异常。

您最好有多个 catch block ...

try{
//}catch (FirstException e) -- I removed this, as you are only catching it and then directly
                        //     throwing it, which seems uneecessary
}catch (RetryException r){
    //process r
    throw r;
}

如果我误解了你的问题,我会尽力纠正。

关于java - 处理异常的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7066404/

相关文章:

java - 类 I/O 的异常(exception)

exception - 除了未处理的异常之外,是什么导致Outlook将COM加载项的LoadBehavior更改为2?

java - 未定义名为 'persistence-unit' 的 bean

java - Java 中的 protected 字段替代方案?

java - 为什么 Java Map<K, V> 为 get 和 remove 方法采用无类型参数?

java - 使用 Selenium 和 SerenityBDD (修昔底德) 进行异常和错误处理的最佳实践

c++ - 以多态方式捕获异常

python - 在 Python 中引发异常

java - byte[]转为图片下载

java - 从 Hibernate hbm.xml 转换为注解