0
0
Rustprogramming~30 mins

Custom error types in Rust - Mini Project: Build & Apply

Choose your learning style9 modes available
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 NegativeNumber
Implement the std::fmt::Display trait for CalcError to show user-friendly messages
Write a function calculate that takes two i32 numbers and returns Result
In calculate, return Err(CalcError::DivideByZero) if dividing by zero
Return Err(CalcError::NegativeNumber) if the first number is negative
Otherwise, return Ok with the division result
Call 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
1
Create the custom error enum
Create an enum called CalcError with two variants: DivideByZero and NegativeNumber.
Rust
Hint

Use enum CalcError { DivideByZero, NegativeNumber } to define the error types.

2
Implement Display for CalcError
Implement the std::fmt::Display trait for CalcError to show these messages: "Cannot divide by zero" for DivideByZero and "Negative number not allowed" for NegativeNumber.
Rust
Hint

Use impl fmt::Display for CalcError and a match to return the messages.

3
Write the calculate function
Write a function called calculate that takes two i32 parameters named a and b and returns Result. Inside, return Err(CalcError::DivideByZero) if b is zero, return Err(CalcError::NegativeNumber) if a is negative, otherwise return Ok(a / b).
Rust
Hint

Use if checks and return Err or Ok accordingly.

4
Call calculate and print the error
Call the function calculate with arguments 10 and 0. Use a match to print the error message if there is an error, or print the result if successful.
Rust
Hint

Use match calculate(10, 0) and print the error with println!("Error: {}", e).