{"id":1095,"date":"2016-09-03T22:40:32","date_gmt":"2016-09-04T05:40:32","guid":{"rendered":"http:\/\/www.certainly-strange.com\/?p=1095"},"modified":"2016-09-03T22:40:32","modified_gmt":"2016-09-04T05:40:32","slug":"error-handling-in-rust","status":"publish","type":"post","link":"http:\/\/www.certainly-strange.com\/?p=1095","title":{"rendered":"Error Handling in Rust"},"content":{"rendered":"<p>There are a lot of things to love about Rust, not least of which are its excellent documentation and package handler (Cargo). But I also really like the error handling.<\/p>\n<p>In Rust, you can choose to handle the error via having the program\u00a0<em>panic<\/em> (which will abort the entire program), but this is generally considered something best avoided &#8211; especially if you are writing a program that other people will be using.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"rust\" data-enlighter-theme=\"twilight\">if n &lt; 1 || n &gt; 10 {\r\n        panic!(\"Invalid number: {}\", n);\r\n    }<\/pre>\n<p>For example, if you had this in your code, and you passed in a number lower than n or greater than 10, you would not get a very good error message and it would be annoying.<\/p>\n<p>An exception would be if the error is raised by something that should not happen and therefore indicating an actual bug in the program (and not simply the user typing the wrong thing, etc). In this case, you would want your program to <em>panic<\/em> and stop everything &#8211; because there is something way wrong that you didn&#8217;t foresee (and so probably could not have written a specific case for it).<\/p>\n<p>You can <em>unwrap<\/em>\u00a0something, which will either return the result of a computation or <em>panic<\/em>. But this, of course, runs into a lot of the same annoying things as panic.<\/p>\n<p>You can also specify that, if you run into an error, for the program to simply continue. For example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"rust\" data-enlighter-theme=\"twilight\">fn main() {\r\n    println!(\"Guess the number!\");\r\n    println!(\"Enter your guess:\");\r\n\r\n    let secret_number = rand::thread_rng().gen_range(1, 101);\r\n    \r\n    loop {\r\n        let mut guess = String::new();\r\n\r\n        io::stdin().read_line(&amp;mut guess)\r\n        .expect(\"Failed to read input\");\r\n\r\n        let guess: u32 = match guess.trim().parse() {\r\n            Ok(num) =&gt; num,\r\n            Err(_) =&gt; continue,\r\n        };\r\n\r\n        println!(\"You guessed {}\", guess);\r\n\r\n        match guess.cmp(&amp;secret_number) {\r\n            Ordering::Less =&gt; println!(\"Higher!\"),\r\n            Ordering::Greater =&gt; println!(\"Lower!\"),\r\n            Ordering::Equal =&gt; {\r\n                println!(\"You Win!\");\r\n                break;    \r\n            }\r\n        }\r\n    }\r\n}<\/pre>\n<p>If the person types in something that is a number, then it will be compared to the randomly generated number and told whether they have won or not. But if the person types in something that is not a number, then the the program will continue and the rest of the <em>loop<\/em> will simply skip and then ask the user to enter another number.<\/p>\n<p>And there are many more ways to handle errors in Rust. You can write error messages for what happens when no arguments were passed when they were expected, or to display a different error if the argument fails to parse (and therefore is not the appropriate type), or to simply proceed as normal if everything checks out:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"rust\" data-enlighter-theme=\"twilight\">fn double_arg(mut argv: env::Args) -&gt; Result&lt;i32, String&gt; {\r\n    argv.nth(1)\r\n        .ok_or(\"Please give at least one argument\".to_owned())\r\n        .and_then(|arg| arg.parse::&lt;i32&gt;().map_err(|err| err.to_string()))\r\n        .map(|n| 2 * n)\r\n}\r\n\r\nfn main() {\r\n    match double_arg(env::args()) {\r\n        Ok(n) =&gt; println!(\"{}\", n),\r\n        Err(err) =&gt; println!(\"Error: {}\", err),\r\n    }\r\n}<\/pre>\n<p>And there are many more ways to write helpful error messages and to handle the errors in such a way that your program behaves the way it should (which includes <em>panic<\/em>-ing when needed). This is just another part of what makes Rust so powerful and such a pleasure to work with.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>There are a lot of things to love about Rust, not least of which are its excellent documentation and package handler (Cargo). But I also really like the error handling. In Rust, you can choose to handle the error via having the program\u00a0panic (which will abort the entire program), but this is generally considered something &hellip; <a href=\"http:\/\/www.certainly-strange.com\/?p=1095\" class=\"more-link\">Continue reading<span class=\"screen-reader-text\"> &#8220;Error Handling in Rust&#8221;<\/span><\/a><\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_crdt_document":"","footnotes":""},"categories":[1],"tags":[],"class_list":["post-1095","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"http:\/\/www.certainly-strange.com\/index.php?rest_route=\/wp\/v2\/posts\/1095","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/www.certainly-strange.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/www.certainly-strange.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/www.certainly-strange.com\/index.php?rest_route=\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"http:\/\/www.certainly-strange.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=1095"}],"version-history":[{"count":2,"href":"http:\/\/www.certainly-strange.com\/index.php?rest_route=\/wp\/v2\/posts\/1095\/revisions"}],"predecessor-version":[{"id":1097,"href":"http:\/\/www.certainly-strange.com\/index.php?rest_route=\/wp\/v2\/posts\/1095\/revisions\/1097"}],"wp:attachment":[{"href":"http:\/\/www.certainly-strange.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=1095"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/www.certainly-strange.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=1095"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/www.certainly-strange.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=1095"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}