Pybites Logo Rust Platform

Custom Error Types

Medium +3 pts

🎯 In Python, you define custom exceptions by subclassing:

class CalcError(Exception):
    pass

class DivisionByZero(CalcError):
    pass

class ParseError(CalcError):
    def __init__(self, token):
        self.token = token

Different error types, but they're all classes in an inheritance hierarchy. You catch the base class or specific ones.

Rust uses enums for error types instead of class hierarchies:

#[derive(Debug, PartialEq, Eq)]
enum CalcError {
    DivisionByZero,
    ParseInt(String),
    BadFormat,
}

Each variant is a distinct error case. The enum carries data when needed (ParseInt(String) stores the bad token). No inheritance, no base class — the match expression handles each case exhaustively.

The ? operator

In exercise …

Login to see the full exercise.