2011-08-15 89 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,直到它被糾正。 –