구조체, 열거형, 트레이트
Rust Error Handling: Result and ?
Errors are values in Rust. Return Result, handle it with match, and pass errors on with ?.
배울 내용
- Ok and Err
- The ? operator
- Your own error messages
parse_and_double("abc")
- 1
text.parse()fails - 2
?returns early - 3
Err(...)the caller gets the error
Success or error, as a value
Rust has no exceptions. A function that can fail returns Result<T, E>, which is either Ok(value) or Err(error). The caller decides what to do with the error.
The ? after parse returns the error to the caller at once when parsing fails; otherwise it gives the number. divide uses a String as its error type and returns Err for a zero divisor. match prints the value or the error message.
핵심 포인트
- Result<T, E> is
Ok(value)orErr(error). - ? returns the error to the caller at once.
- The caller decides what to do.
실행 가능한 Rust 예제
Rust
main.rs
use std::num::ParseIntError;
fn parse_and_double(text: &str) -> Result<i32, ParseIntError> {
let number: i32 = text.trim().parse()?; // ? returns the error early
Ok(number * 2)
}
fn divide(a: i32, b: i32) -> Result<i32, String> {
if b == 0 {
return Err(String::from("cannot divide by zero"));
}
Ok(a / b)
}
fn main() {
for input in ["21", "abc"] {
match parse_and_double(input) {
Ok(value) => println!("{input} -> {value}"),
Err(error) => println!("{input} -> error: {error}"),
}
}
println!("{:?}", divide(10, 2));
println!("{:?}", divide(1, 0));
}
21 -> 42
abc -> error: invalid digit found in string
Ok(5)
Err("cannot divide by zero")연습
예제를 온라인 컴파일러에서 열고 값을 바꾸거나 한 줄을 추가한 다음, 실행하기 전에 출력을 예상해 보세요. 그런 다음 일부러 코드를 망가뜨리고 컴파일러 메시지를 읽어 보세요.
이 레슨을 마쳤나요?
학습 완료로 표시하면 진행 상황을 기록할 수 있습니다.
진행 상황이 이 브라우저에 저장되어 있습니다 로그인하면 모든 기기에서 이어갈 수 있습니다.
챌린지로 연습하기
이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.
- 첫 번째 잘못된 나이 입력한 나이를 검증하고, 프로그램이 중단되기 전에 첫 번째 잘못된 항목이 어디인지 알려줍니다. 쉬움
- 유효한 숫자 더하기 사람이 입력한 데이터는 지저분할 수 있습니다. 문자열 목록이 주어질 때, 오류 없이 `whole numbers`만 더하고 나머지는 무시하세요. 쉬움