I’ve created my own exception but when I try to use it I receive a message saying that it can’t be cast to my exception
I’ve got one interface like this
public interface MyInterface
{
public OtherClass generate(ClassTwo two, ClassThree three) throws RetryException;
}
other like this one
public class MyGenerator{
public class generate (ClassTwo two, ClassThree three){
try{
}catch(MyException my)
}
}
and finally a method in another class
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;
}
}
}
This try catch block on the last method is to make maths operation and I want to catch a division by zero exception on the RetryException.
This line of code is attempting to cast an Exception as a RetryException. This will only work if: RetryException appropriately extends the Exception type that you are catching (ArithmeticException for divide by zero, I think?). AND the Exception actually IS a RetryException. Without looking at more of your logic, we have no idea if this is true.
Try checking
Before you do this cast. Your code may be throwing a different kind of Exception.
Preferably, you would instead have multiple catch blocks…
If I misunderstood your question, I’ll do my best to correct this.