Create custom exception
Rust Programming Language
Problem
In Rust, the concept of exceptions is not present. Instead, Rust uses the Result type to handle errors. The Result type is an enumeration that represents either a success (Ok) or a failure (Err) of an operation.
However, it is possible to create custom error types by defining new enum types that implement the Error trait. Here's an example of how to create a custom error type.
Input
use std::error::Error;use std::fmt;#[derive(Debug)]enum CustomError {FileNotFound(String),InvalidFileFormat,}impl fmt::Display for CustomError {fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {match self {CustomError::FileNotFound(filename) => write!(f, "File not found: {}", filename),CustomError::InvalidFileFormat => write!(f, "Invalid file format"),}}}impl Error for CustomError {}fn read_file(filename: &str) -> Result<String, Box<dyn Error>> {if filename == "nonexistent.txt" {return Err(Box::new(CustomError::FileNotFound(filename.to_string())));}if filename.ends_with(".txt") {Ok(String::from("File contents"))} else {Err(Box::new(CustomError::InvalidFileFormat))}}fn main() {match read_file("test.txt") {Ok(contents) => println!("{}", contents),Err(e) => println!("Error: {}", e),}match read_file("test.jpg") {Ok(contents) => println!("{}", contents),Err(e) => println!("Error: {}", e),}match read_file("nonexistent.txt") {Ok(contents) => println!("{}", contents),Err(e) => println!("Error: {}", e),}}{codeBox}
Output
File contentsError: Invalid file formatError: File not found: nonexistent.txt{codeBox}
Explanation
In this example, we define a custom error type called CustomError that has two variants: FileNotFound, which takes a String argument representing the name of the file that was not found, and InvalidFileFormat, which represents an invalid file format.
We implement the Error trait for the CustomError enum, which requires us to implement the Debug and Display traits. The Display trait is used to format the error message when it is printed.
We then define a function called read_file that takes a filename as an argument and returns a Result<String, Box<dyn Error>>. If the file is not found, we return an Err containing a CustomError::FileNotFound instance. If the file format is invalid, we return an Err containing a CustomError::InvalidFileFormat instance. If the file is found and has a valid format, we return an Ok containing the file contents.
Finally, in the main function, we use the match statement to handle the results of the read_file function. If the result is an Ok, we print the file contents. If the result is an Err, we print the error message.