简体   繁体   中英

No-argument constructor in Exception or its subclasses

Can somebody help me understand the real use case of no-argument constructor in the context of at least exception classes.

EDIT:

As most of the guys said "it helps in the context where the exception class is self explanatory ie NullPonterException , InterruptedException ." Apart from this use case any thing else that we can think of.

Some exceptions are self-explanatory, and their stack trace is all that is necessary to understand them. NullPointerException is one example.

In general, a default constructor is considered to be used, in case that you want to create an object with default values. Concerning default constructors and exceptions, there is already a good answer from Paul Bellora, which I totally agree, but not recommend to use. The reason for is, that you as a programmer are responsible for informing the user about what he did wrong so that he can enhance his input or interaction with the system. Only displaying a dialog which tells the user 'NullPointerException' is just enough for a hello world example! If I implement a custom exception class, I never provide a non argument constructor.

I see the advantage of a default constructors in the creation of complex objects whose creation requires a lot of configuration properties. Applying a flood of overloaded constructors or creational methods can be very confusing and is also difficult to maintain. Working with dependency injection is much more convenient and simplifies the configuration of the object a lot. A very important default constructor is the protected default constructor. Especially for providing an API, you have to prevent the creation of an object by using the new operation from outside. The user should be restricted to create an item of the API by using the creational methods of a factory instance. This is the way to specify the proper use of the API. Of course, you not only will use protected no argument constructors for APIs. But in most cases the properties are injected, hence for instance creation no arguments are required!

A special case is the java.util.Date class whose time of creation defines the value of the object. I'm sure, that there are much more application examples for no arguemnt construcotrs, but the one in combination with Exceptions is probably the worst one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM