In C# I want to communicate to the calling method that the parameters passed to an object have caused its instantiation to fail.
// okay
Banana banana1 = new Banana("green");
// fail
Banana banana2 = new Banana("red");
Throw an exception? If so how?
The best way to signal constructor failure is therefore to throw an exception. If you don't have the option of using exceptions, the "least bad" work-around is to put the object into a "zombie" state by setting an internal status bit so the object acts sort of like it's dead even though it is technically still alive.
If an exception is thrown in a constructor, the object was never fully constructed. This means that its destructor will never be called. Furthermore, there is no way to access an object in an error state. The exception will immediately unwind the local variable.
A constructor may well open a file (not necessarily a bad idea) and may throw if the file-open fails, or if the input file does not contain compatible data. It is reasonable behaviour for a constructor to throw an exception, however you will then be limited as to its use.
Parameter-less ConstructorWhen a constructor is declared without any parameter or argument, then it is called a parameter-less constructor. A parameter-less constructor works like a default constructor and this constructor can contain statements, or it can be empty.
throw new ArgumentException("Reason", "param name");
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