I have a class that has a method. The method may fail and I want to throw an exception. Is it bad to define the exception class within the namespace of the class whose function is throwing the exception? I haven't seen a lot of examples of this, but it seems like the "right" (i.e. OO) way to do it? Is there a reason I should avoid this pattern and define each custom exception in its own file?
public class Foo
{
void bar() {
// do something and throw BarException if something bad happens
}
public static class BarException extends Exception {
// rest of class definition
}
}
I think it depends on the possible scope of the Exception
you're creating. If it will only have to do with Foo
, and only Foo
, forever, then creating it as a nested class would be good.
Just make sure it makes sense for something calling Bar
to say:
catch (Foo.BarException e)
instead of
catch (BarException e)
Else, create it as its own standalone class.
As for the namespace, a Java class could be used for namespacing classes, but generally in Java packages are used for namespacing your classes. I would only use a nested class if there is a very high coupling between the main class and the other class.
I would not use this pattern.
Why do you want to do this? Just, because you don't want to create a new file? ;)
In Java you should only ad one public class in one file. Sometimes I add public interfaces into classes, most for event handling.
class MyEvent {
public void registerHandler(MyEvent.Handler h){
//
}
public interface Handler(){
handle();
}
}
In this case I am absolute sure, there wont be any other class using this Interface.
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