我已经创建了自己的异常,但是当我尝试使用它时,我收到一条消息,说它不能转换为我的异常
我有一个这样的界面
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/