C#.NET — True or False: Any class whose instances are thrown using throw must derive (directly or indirectly) from System.Exception.
-
ATrue
-
BFalse
-
COnly for custom exceptions, not framework types
-
DOnly if the exception crosses app-domain boundaries
-
EOnly in checked contexts
Answer
Correct Answer: True
Explanation
Introduction / Context:C# enforces a strong exception type system: the operand of throw must be an instance of System.Exception or a type derived from it. This unifies error handling across the CLR and tooling.
Given Data / Assumptions:
- Throwing is done with the throw statement.
- We refer to managed code (C# on the CLR).
Concept / Approach:All exceptions in C# are System.Exception-based. You define custom exceptions by deriving from System.Exception (typically adding constructors and optional extra data). This design enables consistent catching (catch (Exception)) and consistent metadata (Message, StackTrace, InnerException, etc.).
Step-by-Step Solution:
Declare a custom exception: class MyProblem : Exception { public MyProblem(string msg) : base(msg) {} } Throw it: throw new MyProblem("details"); Catch it polymorphically: catch (MyProblem) { … } or catch (Exception) { … }Verification / Alternative check:Attempt to throw a non-Exception type (e.g., throw 5;). The compiler reports an error: the thrown object must be Exception-derived.
Why Other Options Are Wrong:They add conditions that do not exist (checked contexts, app-domain crossings, framework types vs custom types).
Common Pitfalls:Choosing ApplicationException as a base by default (not recommended); prefer deriving directly from Exception unless a framework guideline requires otherwise.
Final Answer:True