C#.NET — True or False: A constructor can throw exceptions, but it cannot return an error code.

Difficulty: Easy

Correct Answer: True

Explanation:

Introduction / Context:Constructors are special methods that establish a valid state for newly created objects. Unlike ordinary methods, they have no return type and cannot return a value or error code. This item examines how failure is communicated from constructors.

Given Data / Assumptions:

  • We are using standard C# constructors (instance or static).
  • We are not using out parameters for constructor results.

Concept / Approach:Because constructors have no return type, they cannot signal failure by returning special values. Instead, they signal failure by throwing exceptions (for example, ArgumentException, InvalidOperationException, or IOException). If a constructor throws, the object is not considered successfully created, and the runtime unwinds the stack and frees any partially constructed state.

Step-by-Step Solution:

Attempt resource acquisition or validation in the constructor.On failure, throw a descriptive exception.Caller must handle the exception or allow it to propagate.

Verification / Alternative check:Create a constructor that validates a file path; if the file is missing, throw FileNotFoundException. Observe that new T(...) throws and no object is created.

Why Other Options Are Wrong:Answer False would imply that constructors return error codes or that they cannot throw, which contradicts C# semantics and common practices.

Common Pitfalls:Doing heavy work in constructors without proper exception handling can make error diagnosis difficult. Consider factory methods when construction frequently fails.

Final Answer:True

More Questions from Exception Handling

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion