PY
C#

Python to C#

10 lessons

Progress0%
1Variables & Types2Classes & OOP3Collections & LINQ4Async/Await5Exception Handling6File I/O7Generics8Delegates and Events9Records and Pattern Matching10Interfaces
All Mirror Courses
PY
C#
Exception Handling
MirrorLesson 5 of 10
Lesson 5

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.

Mirror Card
PY
From Python:

In Python, you're familiar with error handling patterns.

C#
In C#:

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:

C#
C# 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:

PY
Python (What you know)
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")
Mirror Card
PY
From Python:

You may be used to different syntax or behavior.

C#
In C#:

C# catch specifies exception type; Python uses 'except ExType as e'

Mirror Card
PY
From Python:

You may be used to different syntax or behavior.

C#
In C#:

C# exception filters (when) add conditions; Python uses if inside except

Mirror Card
PY
From Python:

You may be used to different syntax or behavior.

C#
In C#:

C# 'throw;' rethrows with original stack trace; Python 'raise' does the same

Mirror Card
PY
From Python:

You may be used to different syntax or behavior.

C#
In C#:

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.

PY
Python
except AppError as e: print(e.code)
C#
C#
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.

PY
Python
except AppError as e:
    if e.code == 404: ...
C#
C#
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.

PY
Python
except Exception: raise  # bare raise
C#
C#
catch (Exception) { throw; } // bare throw

Common 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
Common Pitfall
Don't assume C# works exactly like Python. While the concepts may be similar, the syntax and behavior can differ significantly.

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
Rule of Thumb
The best way to learn is by doing. Try rewriting some of your Python code in C# to practice these concepts.
PreviousNext