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?
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.
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 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.
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");
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With