C# uses exceptions for exceptional error paths—similar to Java but without checked exceptions. Combine try/catch/finally with using for deterministic resource cleanup via IDisposable.
try / catch / finally
try {
throw new InvalidOperationException("failed");
} catch (InvalidOperationException ex) {
Console.WriteLine(ex.Message);
} finally {
Console.WriteLine("cleanup");
}
Custom exceptions
class AppException : Exception {
public AppException(string message) : base(message) { }
}
Throw specific types; catch the most specific exception first. Use exceptions for unexpected failures—not routine control flow.
Important interview questions and answers
- Q: Exceptions vs Result types?
A: Exceptions unwind the stack for rare failures; Result/either patterns suit expected errors in functional-style APIs. - Q: finally vs using?
A:usingcallsDisposedeterministically;finallyruns on all exit paths including exceptions.
Self-check
- What runs in finally when an exception is thrown?
- Base type for catching all managed exceptions?
Tip: Catch specific exceptions first—avoid empty catch blocks that swallow errors and hide bugs in production.
Interview prep
- finally purpose?
Runs whether or not an exception is thrown—use for cleanup; prefer
usingfor disposable resources.- throw vs throw ex?
throw;preserves the original stack trace;throw ex;resets it—rethrow with barethrow.