Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java defining custom exceptions inside of class, is this bad?

Tags:

java

exception

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
    }
}
like image 710
Josh Petitt Avatar asked Oct 11 '13 20:10

Josh Petitt


2 Answers

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.

like image 159
rgettman Avatar answered Sep 30 '22 18:09

rgettman


I would not use this pattern.

  • You add more line to class.
  • This class has more than one concern
  • and you will get problems, if you want to use the same Exception in another class.

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.

like image 28
Christian Kuetbach Avatar answered Sep 30 '22 17:09

Christian Kuetbach