Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exceptions as public classes vs. public static inner classes

I have two options (which technically are the same, as I understand) to declare a custom exception class thrown only from a particular class com.XXX.Foo:

  • as a public class in the package: com.XXX.CustomException
  • as a public static inner class: com.XXX.Foo.CustomException

Which option is better?

like image 389
yegor256 Avatar asked Nov 15 '10 10:11

yegor256


People also ask

What is the difference between inner class and static inner class?

Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class.

Can inner classes be public?

Java inner class is defined inside the body of another class. Java inner class can be declared private, public, protected, or with default access whereas an outer class can have only public or default access.

What is the difference between inner class and nested class?

In Java programming, nested and inner classes often go hand in hand. A class that is defined within another class is called a nested class. An inner class, on the other hand, is a non-static type, a particular specimen of a nested class.


1 Answers

In case the exception is very specific to Foo class, I don't mind keeping it as a public Nested class. And whenever it seems like a time to extract that out, simply extract that out.

In general practice, I have never seen any nested class defined for Exception, though. I also don't know if one exist in Java API.

like image 89
Adeel Ansari Avatar answered Oct 11 '22 23:10

Adeel Ansari