Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to communicate that your constructor has failed in C#?

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?

like image 767
Justin Tanner Avatar asked Jan 23 '09 00:01

Justin Tanner


People also ask

How can I handle a constructor that fails?

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.

What happens when a constructor fails in C++?

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.

Can constructor fail?

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.

Can constructors be Parameterless?

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.


1 Answers

throw new ArgumentException("Reason", "param name");
like image 150
Serafina Brocious Avatar answered Sep 22 '22 19:09

Serafina Brocious