Skip to content

Commit e634d21

Browse files
Add examples for std::Error module
1 parent 46e7f4b commit e634d21

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

src/libstd/error.rs

+70
Original file line numberDiff line numberDiff line change
@@ -66,10 +66,80 @@ pub trait Error: Debug + Display + Reflect {
6666
/// The description should not contain newlines or sentence-ending
6767
/// punctuation, to facilitate embedding in larger user-facing
6868
/// strings.
69+
///
70+
/// # Examples
71+
///
72+
/// ```
73+
/// use std::error::Error;
74+
///
75+
/// match "xc".parse::<u32>() {
76+
/// Err(e) => {
77+
/// println!("Error: {}", e.description());
78+
/// }
79+
/// _ => println!("No error"),
80+
/// }
81+
/// ```
6982
#[stable(feature = "rust1", since = "1.0.0")]
7083
fn description(&self) -> &str;
7184

7285
/// The lower-level cause of this error, if any.
86+
///
87+
/// # Examples
88+
///
89+
/// ```
90+
/// use std::error::Error;
91+
/// use std::fmt;
92+
///
93+
/// #[derive(Debug)]
94+
/// struct SuperError {
95+
/// side: SuperErrorSideKick,
96+
/// }
97+
///
98+
/// impl fmt::Display for SuperError {
99+
/// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
100+
/// write!(f, "SuperError is here!")
101+
/// }
102+
/// }
103+
///
104+
/// impl Error for SuperError {
105+
/// fn description(&self) -> &str {
106+
/// "I'm the superhero of errors!"
107+
/// }
108+
///
109+
/// fn cause(&self) -> Option<&Error> {
110+
/// Some(&self.side)
111+
/// }
112+
/// }
113+
///
114+
/// #[derive(Debug)]
115+
/// struct SuperErrorSideKick;
116+
///
117+
/// impl fmt::Display for SuperErrorSideKick {
118+
/// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
119+
/// write!(f, "SuperErrorSideKick is here!")
120+
/// }
121+
/// }
122+
///
123+
/// impl Error for SuperErrorSideKick {
124+
/// fn description(&self) -> &str {
125+
/// "I'm SuperError side kick!"
126+
/// }
127+
/// }
128+
///
129+
/// fn get_super_error() -> Result<(), SuperError> {
130+
/// Err(SuperError { side: SuperErrorSideKick })
131+
/// }
132+
///
133+
/// fn main() {
134+
/// match get_super_error() {
135+
/// Err(e) => {
136+
/// println!("Error: {}", e.description());
137+
/// println!("Caused by: {}", e.cause().unwrap());
138+
/// }
139+
/// _ => println!("No error"),
140+
/// }
141+
/// }
142+
/// ```
73143
#[stable(feature = "rust1", since = "1.0.0")]
74144
fn cause(&self) -> Option<&Error> { None }
75145

0 commit comments

Comments
 (0)