Error Handling (Rust)
Panic
panic!
๋งคํฌ๋ก๋ ํ๋ก๊ทธ๋จ์์ ์๋ฌ๋ฅผ ์ผ์ผํจ๋ค.panic!
๋งคํฌ๋ก๊ฐ ๋์ํ๋ฉด ํ๋ก๊ทธ๋จ์ ์คํจ ๋ฉ์์ง๋ฅผ ์ถ๋ ฅํ๊ณ ์คํ์ ๋๊ฐ๋๋ค.
fn main() {
panic!("crash and burn");
}
Result
-
๋๋ถ๋ถ์ ์๋ฌ๋ ํ๋ก๊ทธ๋จ์ ์ค๋จํด์ผ ํ ์ ๋๋ก ์ฌ๊ฐํ์ง๋ ์๋ค.
-
ํจ์๊ฐ ์คํจํ๋ฉด
Result
์ด๊ฑฐํ์ ๋ฐํํ๋๋ก ํ๋ค.enum Result<T, E> { Ok(T), Err(E), }
-
ํจ์๊ฐ ๋ฐํํ
Result
์ ๋ฐ๋ผ ๋ถ๊ธฐ๋ฅผ ํ๋ค.let file = File::open("data"); let file = match file { Ok(f) => f, Err(error) => { panic!("Failed to open the file: {:?}", error) }, }
-
Result
์์ ๋ฐํํ ์๋ฌ์ ์ข ๋ฅ์ ๋ฐ๋ผ ๋ค์ ๋ถ๊ธฐํ ์๋ ์๋ค.let file = File::open("data"); let file = match file { Ok(f) => f, Err(error) => match error.kind() { ErrorKind::NotFound => match File::create("data") { Ok(fc) => fc, Err(e) => panic!("Failed to create file: {:?}", e), }, other_error => panic!("Failed to open file: {:?}", other_error), }, };
-
unwrap
-Result
๊ฐOk
๋ฉดOk
์ ๊ฐ์ ๋ฐํ,Err
์ด๋ฉดpanic!
๋งคํฌ๋ก๋ฅผ ํธ์ถ.let file = File::open("data").unwrap();
-
expect
-unwrap
๊ณผ ๋น์ทํ์ง๋งpanic!
์ ์๋ฌ ๋ฉ์์ง๋ฅผ ์ง์ ์ค์ ํ ์ ์๋ค.let file = File::open("data").expect("Failed to open file");
-
?
-Result
๊ฐOk
๋ฉดOk
์ ๊ฐ์ ๋ฐํ,Err
์ด๋ฉด ํธ์ถ๋ถ์Err
์ ๋ฐํํ๋ค. (์ด๋ ํจ์๋ ๋ฐ๋์Result
ํ์ ์ ๋ฐํํด์ผ ํ๋ค.)fn open_file() -> Result<String, io::Error> { let file = File::open("data")?; Ok(file) }