error handling - What is the right way to capture panics? -


frequently don't want our program stopping due out of bounds, division 0 or similar panics. however, std::thread::catch_panic marked unstable. write...

let result = thread::scoped(move || {         make_a_division_for_ever()     }).join();     if result.is_ok() {         println!("finished ok");     } 

is right way capture panics (like division 0 or out of bounds)?

a complete example...

use std::thread::thread;  fn main() {     println!("make divisions ever");      loop {         let result = thread::scoped(move || {             make_a_division_for_ever()         }).join();         if result.is_ok() {             println!("finished ok");         }         else {             println!("it crashed!!!  restarting...");         }     }  }  fn make_a_division_for_ever() {     loop {         println!("enter divisor...");         let line = std::io::stdin()                 .read_line()                 .ok()                 .expect("error reading line");          let divisor = line.trim()                 .parse::<u32>()                 .expect(" coudn't parse line string. i'm going die showed things closer orion belt...         ");          println!("readed {}", divisor);          let dangerous =  1_000_000 / divisor;          println!("div result... {}", dangerous);     } } 

rust panics aren't intended caught in cases. unstable rust provides functionality, should using if have complex situation (say, you're writing test harness other rust programs , need hook panic handler) can't bubble error.

in rust, error handling done returning result<t,e>s (sometimes option<t>, bubbling them try!(), , handling them match.

most panicky methods have non-panicky versions; example checked version of divide checked_div(), , can use try! return errors string parsing.


Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -