WiredDrummer
WiredDrummer

Reputation: 23

Exception type created class used in another

I can't seem to find a way to fix this. I have a class called CardException which extends Exception. The only code it has is:

public class CardException extends Exception{

String erro;

public CartaoException(String erro){
    this.erro = erro;
}
}

Now I have another class with a method in which I want to throw an Exception if the condition is false:

public void changePin(int pin, int newPin){
    try{
        if(pin == getPin()){
            setPin(newPin);
        }
    } catch (CardException e){
        System.out.println(e.getMessage());
    }
}

but I'm getting an error at "catch (CardException e)" saying: "Unreachable catch block for CardException. This exception is never thrown from the try statement body" and I have no idea why.

The point is to create a class called CardException of Exception type, with a constructor that receives an error message as argument. Then, on my other class, I need to create that method changePin which receives the old pin and a new pin and, if the old pin doesn't match the one already saved, it has to throw and exception with a message: "Invalid pin".

Upvotes: 2

Views: 47

Answers (2)

Juned Ahsan
Juned Ahsan

Reputation: 68715

Java compiler is intelligent enough to determine whether the statements inside try blocks are prone to a checked exception or not. As no statement in your try block seems to cause CardException, hence compiler complains.

Just for the sake of testing, if you add throws clause with CardException to either of your getPin/setPin method, then compiler will not complain as those methods can throw the exception in catch block.

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727027

Since CardException extends Exception, not RuntimeException, it is considered a checked exception. What that means is that all methods from which the exception is thrown must declare the exception in their throws declaration clause.

Because of this requirement Java compilers can check if a code block throws a particular checked exception or not:

  • If there is a throws block inside the code body that throws this exception or one of its subclasses, the catch is valid
  • If any of the functions called inside the code body is declared as throwing the exception or one of its subclasses, the catch is valid
  • Otherwise, the catch is invalid, and the compiler issues an error.

You would need to catch this exception if getPin or setPin threw it. In this case, however, the functions would need to add a throws CardException to their declarations.

Upvotes: 1

Related Questions