2011-08-15 91 views
5

我已经建立了我自己的异常,但是当我尝试使用它,我收到一条消息说,它不能转换到我的例外问题处理异常

我有一个接口,这样

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块是要对数学进行操作,我想通过在RetryException零异常赶上一个部门。

+4

说whaaaaaaaa O_O – mre

+0

我固定的代码标签,然后有人在我身后编辑弄乱了.... –

+1

大干一场来解决这一职务。 – James

回答

6
RetryException retry= (RetryException)x; 

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

尝试检查

if (x instanceof RetryException) 

在你做这个转换。你的代码可能会抛出一种不同的异常。

最好,你反而会拥有多个catch块...

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; 
} 

如果我误解了你的问题,我会尽我所能来纠正这一点。

+0

山姆DeHaan在我的代码异常遵循此树'异常 - > MyFirstException - > RetryException' – alculete

+0

所以,没有人有我的解决方案? – alculete

+0

它是什么归结到这一点:你试图将一个异常转换为RetryException('(RetryException)x')。该异常不一定是RetryException,所以这是失败的。我们提供了一些解决方案,但是您没有接受它们,或者提供了他们无法工作的原因。 –

4

,我要在这里做一些大的假设,所发生的事情,因为代码的例子是非常不完整。

在你的评价方法,您得到的ArithmeticException由于零一分,并且希望通过抛出处理自己RetryException来处理它。收到的异常不能被铸造,因为它的类型是错误的,你应该在你的evaluate方法中捕获ArithmeticException,然后创建并抛出一个新的RetryException。

public Object evaluate(String expression, Map values) throws FirstException, RetryException 
{ 
    try{ 
     // Some code that may throw FirstException 
     int x = 10/0; 
    }catch (ArithmeticException x){ // Handle divide by zero 
     RetryException retry= new RetryException(); 
     retry.setExpression(expression); 
     retry.setPosition(position); 
     retry.setOperator(tokens[position]); 
     retry.setOperand(1); 
     throw retry; 
    } 
    } 
} 

这一切都假设当然存在适当的设置方法的适当的RetryException。除去

FirstException抓,因为它是通过隐藏,需要时没有创建新实例的实际堆栈跟踪。它已经在方法签名中声明并且没有实际的处理。

+0

一个很好的答案,但Java代码格式不正确。 'setProperty()= x'应该是'setProperty(x)' –

+0

@Sam DeHaan是的,我只是在重构OP的代码,并且有点仓促。感谢您指出,它现在已经修复。 – Robin

+0

是的,重构是很好的,只是不想+1,直到它被纠正。 –