处理异常的问题

alc*_*ete 5 java exception

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

我有一个像这样的界面

public interface MyInterface
{   
    public OtherClass generate(ClassTwo two, ClassThree three) throws RetryException;
}
Run Code Online (Sandbox Code Playgroud)

其他像这样的

public class MyGenerator{   
  public class generate (ClassTwo two, ClassThree three){
    try{
    }catch(MyException my)
  }
}
Run Code Online (Sandbox Code Playgroud)

最后是另一个类中的方法

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; 
     }
  }
}
Run Code Online (Sandbox Code Playgroud)

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

Sam*_*aan 6

RetryException retry= (RetryException)x; 
Run Code Online (Sandbox Code Playgroud)

这行代码试图将Exception强制转换为RetryException.这只有在以下情况下才会起作用:RetryException适当地扩展了你捕获的Exception类型(ArithmeticException为除以零,我想?).和Exception实际上是一个RetryException.如果不考虑更多的逻辑,我们不知道这是否属实.

试试看

if (x instanceof RetryException)
Run Code Online (Sandbox Code Playgroud)

在你做这个演员之前.您的代码可能会抛出不同类型的异常.

最好是你会有多个捕获块......

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;
}
Run Code Online (Sandbox Code Playgroud)

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