Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a standard exception to be thrown if object is not instance of something in java?

Let's 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 throw or should I create my own exception class for this?

like image 968
lsund Avatar asked Oct 23 '14 15:10

lsund


People also ask

Can any object be thrown as an exception?

You can't throw just any object as an exception, however, only objects whose class descends from Throwable . Throwable serves as the base class for an entire family of classes, declared in java. lang , that your program can instantiate and throw.

Can you throw a general exception in Java?

You can throw a more general exception, or a more specific exception. For simpler methods, more general exceptions are enough. If the method is complex, then, throwing a more specific exception will be reliable.

What happens when an exception object is not caught and handled properly?

What happens if an exception is not caught? If an exception is not caught (with a catch block), the runtime system will abort the program (i.e. crash) and an exception message will print to the console.


2 Answers

Although somewhat opinion-based, the usual exception to throw when an object is not the expected type is ClassCastException, and this approach is used fairly widely in the JDK. You could go one better than the JDK though and provide a message:

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

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

throw new IllegalArgumentException("myParameter was not of type Bar");
like image 95
Bohemian Avatar answered Sep 21 '22 07:09

Bohemian


Regarding your question:

Is this reasonable programming? You have an opportunity to make use of Strategy pattern as described http://www.tutorialspoint.com/design_pattern/strategy_pattern.htm.

It will remove your need for if and else checking, instead you inject appropriate type of object (implementing same interface) and call respective method. It will also ensure you wont need to change you code with another if else block basically following open for extension closed for modification.

Regarding exception if you want to stick with code above you could throw IllegalArgumentException.

like image 32
SMA Avatar answered Sep 20 '22 07:09

SMA