Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Custom exceptions: Package convention?

Tags:

java

exception

When creating a custom exception class (e.g. a custom runtime exception), is there a specific convention for where within the folder/package structure to create it?

Should all the custom exception classes be within the same package?

like image 454
rni902 Avatar asked Nov 02 '15 15:11

rni902


People also ask

Should exceptions be in a separate package?

It would be a bad practice and will lead to unnecessary inter package dependencies. A custom exception class should always be defined in the same package as the classes which are capable of throwing it. You should try to minimize creating custom exception which are used all over the application, for that use Exception.

How do I create an exception to a package in Java?

To create the exception object, the program uses the throw keyword followed by the instantiation of the exception object. At runtime, the throw clause will terminate execution of the method and pass the exception to the calling method. Save your file as TestDivideByZeroException. java .

What is the package for exceptions in Java?

The java. lang. Exceptions provides for different exceptions thrown under java lang package.

How do you create customized exceptions in Java?

In order to create a custom exception, we need to extend the Exception class that belongs to java. lang package. Example: We pass the string to the constructor of the superclass- Exception which is obtained using the “getMessage()” function on the object created.


1 Answers

An exception class should always be defined in the same package as the classes which are capable of throwing it. Never create a separate package just to hold exceptions.

In general, a package should encapsulate a single major unit of functionality. Exceptions are part of that functionality.

Subpackages should only be created to limit access to classes and/or methods. This is done by creating "package access" classes and/or methods: they are neither public, nor protected, nor private. Having no access modifier means they are visible only to classes in the same package. If you don't have any such classes or methods, you probably shouldn't be making a subpackage.

Subpackages should not be created for:

  • grouping a few classes that happen to have some things in common. (Notice there's no java.text.format or java.net.socket or javax.swing.button package in Java SE.)
  • breaking up a package because it seems to have too many classes in it. (There's nothing wrong with having fifty classes in one package.)
like image 159
VGR Avatar answered Sep 29 '22 09:09

VGR