Is there a standard exception if the object is not an instance of something in java?

Say I have the following:

public interface Foo {
    ...
}

public class Gin {
    ...
}

public class Fizz {
    ...
}

public class Buzz {
    public Foo getAFoo() {
        ...
    }

    public void test() {
        Foo myfoo = getAFoo();
        if (myFoo instanceof Bar) {
            Bar myBar = (Bar) myFoo;
            //do something more
        } else {
        //throw new something exception
        }
    }
}

Is this reasonable programming? Is there a built-in exception that test () can execute, or should I create my own exception class for it?

+4
source share
3 answers

Despite some opinion-based opinion, the usual exception is when the object is not the expected type ClassCastException, and this approach is pretty widely used in the JDK. You could go better than the JDK and provide a message:

throw new ClassCastException("Object was not of type Bar");

If the object is passed as a parameter, you can use IllegalArgumentException, also with the message:

throw new IllegalArgumentException("myParameter was not of type Bar");
+4

:

? , http://www.tutorialspoint.com/design_pattern/strategy_pattern.htm.

if else, ( ) . , , else , .

, , IllegalArgumentException.

+2

, .

- :

error: incompatible types: Bar cannot be converted to Foo  

interface Foo extend Bar

, , .

But if you are just IMAGINE for any such thing to be legal in Java, you must create a custom exception. Coz there is no such built-in exception class designed for such errors.

0
source

All Articles