When creating an exception class is it okay to only provide a "specific" constructor:
public CircularLinkException(final String msg, final String link)
{
super(msg);
link = inputName;
}
or should I implement the constructors of Exception
:
public class CircularLinkException extends Exception
{
public CircularLinkException() { /* ... */ }
public CircularLinkException(final String msg) { /* ... */ }
public CircularLinkException(final Throwable t) { /* ... */ }
public CircularLinkException(final String msg, final Throwable t) { /* ... */ }
}
The short answer to the question “can a constructor throw an exception in Java” is yes! Of course, properly implementing exceptions in your constructors is essential to getting the best results and optimizing your code.
The class Exception contains two constructors.
Always create your own exception classes. Like any other class, an exception class can contain fields and methods. The new exception class should extend RuntimeException if the program should be required to handle the exception.
When throwing an exception in a constructor, the memory for the object itself has already been allocated by the time the constructor is called. So, the compiler will automatically deallocate the memory occupied by the object after the exception is thrown.
You should create all the Constructors you will use.
Don't add code when you imagine a use for something. Add it when you have a requirement for it.
http://c2.com/xp/YouArentGonnaNeedIt.html
It is not actually required to implement any particular constructor. One arbitrary can be implemented in order to construct the exception at all.
Usually two cases happen:
I think, the version without parameters and the version that takes Throwable only are more for lazy people and you just enforce more order in your code by not implementing these.
If your specific exception benefit from some additional information that is always available, surely the constructor should have additional parameters, forcing to pass this information. In your case, a version with the two string parameters should be preserved but probably a version that also takes Throwable as a third parameter would be good. Many known exceptions (like IOException, for instance) went through the pain from "we will never need this kind of constructor" towards adding such constructor in the later versions.
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