Custom error types
📖 Scenario: Imagine you are writing a small program that processes user input for a simple calculator. You want to handle errors clearly by creating your own error type.
🎯 Goal: You will create a custom error type called CalcError with two variants, then write a function that returns this error type, and finally print the error message.
📋 What You'll Learn
Create an enum called
CalcError with variants DivideByZero and NegativeNumberImplement the
std::fmt::Display trait for CalcError to show user-friendly messagesWrite a function
calculate that takes two i32 numbers and returns ResultIn
calculate, return Err(CalcError::DivideByZero) if dividing by zeroReturn
Err(CalcError::NegativeNumber) if the first number is negativeOtherwise, return
Ok with the division resultCall
calculate with values 10 and 0 and print the error message💡 Why This Matters
🌍 Real World
Custom error types help programs explain problems clearly to users or other parts of the program.
💼 Career
Understanding how to create and use custom errors is important for writing robust and maintainable Rust applications.
Progress0 / 4 steps