Exception Handling
Error handling patterns
Introduction
In this lesson, you'll learn about exception handling in C#. Coming from Python, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In Python, 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; }
}
public User GetUser(int userId) {
if (userId <= 0) throw new AppException("Invalid ID", 400);
if (!db.ContainsKey(userId)) throw new AppException("Not found", 404);
return db[userId];
}
try {
var user = GetUser(42);
} catch (AppException ex) when (ex.Code == 404) {
Console.WriteLine("Not found: " + ex.Message);
} catch (AppException ex) {
Console.WriteLine("Error " + ex.Code + ": " + ex.Message);
} catch (Exception) {
throw; // rethrow
} finally {
Console.WriteLine("always runs");
}Comparing to Python
Here's how you might have written similar code in Python:
class AppError(Exception):
def __init__(self, message: str, code: int):
super().__init__(message)
self.code = code
def get_user(user_id: int):
if user_id <= 0:
raise AppError("Invalid ID", 400)
if user_id not in db:
raise AppError("Not found", 404)
return db[user_id]
try:
user = get_user(42)
except AppError as e:
print(f"Error {e.code}: {e}")
except Exception as e:
raise # re-raise
finally:
print("always runs")You may be used to different syntax or behavior.
C# catch specifies exception type; Python uses 'except ExType as e'
You may be used to different syntax or behavior.
C# exception filters (when) add conditions; Python uses if inside except
You may be used to different syntax or behavior.
C# 'throw;' rethrows with original stack trace; Python 'raise' does the same
You may be used to different syntax or behavior.
C# has both checked and unchecked exceptions; Python has only runtime exceptions
Step-by-Step Breakdown
1. Typed Catch
C# catch clauses specify the exception type directly, like Python's 'except AppError as e' syntax.
except AppError as e: print(e.code)catch (AppException ex) { Console.WriteLine(ex.Code); }2. Exception Filters
C#'s when clause adds a condition to a catch block, replacing Python's if statement inside except.
except AppError as e:
if e.code == 404: ...catch (AppException ex) when (ex.Code == 404) { ... }3. Rethrowing
Both C# 'throw;' and Python 'raise' (bare) rethrow the current exception preserving the original stack trace.
except Exception: raise # bare raisecatch (Exception) { throw; } // bare throwCommon Mistakes
When coming from Python, developers often make these mistakes:
- C# catch specifies exception type; Python uses 'except ExType as e'
- C# exception filters (when) add conditions; Python uses if inside except
- C# 'throw;' rethrows with original stack trace; Python 'raise' does the same
Key Takeaways
- except ExType as e → catch (ExType ex)
- Exception filters: when (condition) replace if inside except
- Bare throw; = Python bare raise
- finally works identically in both languages