How do I ignore an error returned from a Rust function and proceed regardless?

  • A+
Category:Languages

When it is known that some piece of code might throw an error, we make use of try/catch blocks to ignore such errors and proceed. This is done when the error is not that important but maybe we only want to log it:

try{     int i = 1/0; } catch( ArithmeticException e){     System.out.println("Encountered an error but would proceed."); }  x = y; 

Such a construct in Java would continue on to execute x = y;.

Can I make use of match to do this or any other construct?

I do see a try! macro, but perhaps it would return in case of an error with the return type of the method as Result.

Edit: I want to use such a construct in a UT to ensure it continues to run even after an error has occured.

 


Functions in Rust which can fail return a Result:

Result<T, E> is the type used for returning and propagating errors. It is an enum with the variants, Ok(T), representing success and containing a value, and Err(E), representing error and containing an error value.

I highly recommend reading the Rust book:

Rust has a number of features for handling situations in which something goes wrong

If you want to ignore an error, you have different possibilities:

  • Don't use the Result:

    let _ = failing_function(); 

    The function will be called, but the result will be ignored.

  • Ignore the Err variant of Result using if let or match:

    if let Ok(ret) = failing_function() {     // use the returned value } 
  • Unwrap the error. This code panics if an error occurred though:

    let ret = failing_function().unwrap(); // or let ret = failing_function().expect("A panic message to be displayed"); 

try!() unwraps a result and early returns the function, if an error occurred. However, it's more idiomatic to use ? instead of try!.


See also:

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: