Exception Handling
Error handling patterns
Introduction
In this lesson, you'll learn about exception handling in C#. Coming from JavaScript, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In JavaScript, you're familiar with error handling patterns.
C# has its own approach to error handling patterns, which we'll explore step by step.
The C# Way
Let's see how C# handles this concept. Here's a typical example:
public class AppException : Exception {
public int Code { get; }
public AppException(string message, int code)
: base(message) { Code = code; }
}
try {
if (user == null) throw new AppException("Not found", 404);
ProcessUser(user);
} catch (AppException ex) when (ex.Code == 404) {
Console.WriteLine("Not found: " + ex.Message);
} catch (AppException ex) {
Console.WriteLine(ex.Code + ": " + ex.Message);
} catch (Exception ex) {
throw; // rethrow preserving stack trace
} finally {
Cleanup();
}Comparing to JavaScript
Here's how you might have written similar code in JavaScript:
class AppError extends Error {
constructor(message, code) {
super(message);
this.code = code;
this.name = "AppError";
}
}
try {
if (!user) throw new AppError("Not found", 404);
processUser(user);
} catch (err) {
if (err instanceof AppError) {
console.log(err.code, err.message);
} else {
throw err;
}
} finally {
cleanup();
}You may be used to different syntax or behavior.
C# catch clauses specify types; JS uses instanceof inside catch
You may be used to different syntax or behavior.
C# exception filters (when clause) add conditions to catch
You may be used to different syntax or behavior.
C# 'throw;' (bare) rethrows preserving stack trace; 'throw ex;' resets it
You may be used to different syntax or behavior.
C# Exception has InnerException for wrapping; JS uses error.cause
Step-by-Step Breakdown
1. Typed Catch
C# catch clauses specify the exception type directly, replacing JS's instanceof check inside a generic catch.
catch (err) { if (err instanceof AppError) { ... } }catch (AppException ex) { ... } // type-specific2. Exception Filters
The 'when' clause adds a condition to a catch block — only catches if the condition is true.
catch (AppException ex) when (ex.Code == 404) {
// only runs for 404 errors
}3. throw vs throw ex
Bare 'throw;' rethrows the current exception preserving the original stack trace. 'throw ex;' resets it to the current location.
Common Mistakes
When coming from JavaScript, developers often make these mistakes:
- C# catch clauses specify types; JS uses instanceof inside catch
- C# exception filters (when clause) add conditions to catch
- C# 'throw;' (bare) rethrows preserving stack trace; 'throw ex;' resets it
Key Takeaways
- Typed catch replaces instanceof checks
- when clause filters exceptions by condition
- throw; preserves stack trace; throw ex; resets it
- Exception wrapping via InnerException