Rust Reference ยท Errors, Panics and Process
Parse and conversion errors in Rust
Reference for Rust parse and conversion errors: ParseIntError kinds, ParseFloatError, ParseBoolError, ParseCharError, TryFromIntError and how to handle them.
Turning text or one numeric type into another can fail, and the standard library reports each kind of failure with a small dedicated error type. str::parse returns the error type of the target's FromStr implementation, and TryFrom or try_into return TryFromIntError when a number does not fit.
All of these types implement Debug, Display, Clone, PartialEq and std::error::Error, so they work with ? and Box<dyn Error>. None of them carries the input that failed; if you want to show it, add it yourself with map_err.
let a = "42".parse::<i32>(); // Ok(42) let b = "4x2".parse::<i32>(); // Err(ParseIntError { kind: InvalidDigit }) let c = u8::try_from(300_i32); // Err(TryFromIntError(()))
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
The error types
| Type | Produced by | Notes |
|---|---|---|
ParseIntError |
parse::<i32>() and all integer types, from_str_radix |
kind() returns an IntErrorKind: Empty, InvalidDigit, PosOverflow, NegOverflow, Zero (for NonZero types). |
ParseFloatError |
parse::<f32>(), parse::<f64>() |
Two cases, empty string and invalid number; the kind is private. |
ParseBoolError |
parse::<bool>() |
Only "true" and "false" (lowercase) are accepted. |
ParseCharError |
parse::<char>() |
Fails for an empty string or more than one char. |
TryFromIntError |
TryFrom between integer types |
Also returned by try_into(); no detail about which side overflowed. |
CharTryFromError |
char::try_from(u32) |
The value is not a Unicode scalar value (surrogate or above U+10FFFF). |
TryFromSliceError |
<[T; N]>::try_from(&[T]) |
The slice has the wrong length. |
Infallible |
TryFrom for types where From exists |
An error type that cannot occur. |
Usage notes
- Whitespace is not trimmed.
" 7".parse::<i32>()fails; call.trim()first. - A leading
+is accepted for integers; a leading-is rejected for unsigned types withInvalidDigit, even for"-0". - Float parsing accepts
inf,infinityandnanin any case, and exponents like1e3. It does not accept a decimal comma or thousands separators. - For other bases use
i32::from_str_radix(text, 16); prefixes like0xare not understood and causeInvalidDigit. ascasts never fail: they truncate or saturate silently. Usetry_fromwhen a lossy conversion would be a bug.- Because the errors do not store the input, wrap them:
text.parse::<u16>().map_err(|e| format!("port {text:?}: {e}")). - Matching on
IntErrorKindlets you give different messages to "empty" and "too large"; the enum is#[non_exhaustive], so keep a_arm. unwrap_or_default()after.parse().ok()is a quick way to treat bad input as 0, but hides mistakes; use it deliberately.