Error Handling Flashcards

1
Q

What are the two major categories Rust groups errors into?

A

recoverable and unrecoverable.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What does Rust have for recoverable errors?

A

Result

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What does Rust have for unrecoverable errors?

A

panic!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What happens when the panic! macro executes?

A

Failure message is printed, stack is unwound and cleaned up, and then program quits.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How can you prevent a program from performing expensive unwinding on panic!

A

By having it abort instead. Add panic = ‘abort’ to the appropriate profile sections in the Cargo.toml.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is a backtrace?

A

A list of all the functions that were called leading to the failure point.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How is the Result enum defined?

A

enum Result {
Ok(T),
Err(E),
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What does unwrap() do with the Result type?

A

Returns the T value inside the Ok if present, else, if an E or None is present then it will panic.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What does the expect() do with the Result type?

A

Returns the T value inside the Ok if present, else, if an E or None is present will panic! with a user defined message.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Provide an example statement using the expect().

A

let f = File::open(“hello.txt”).expect(“Failed to open hello.txt”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is propagating an error?

A

Returning an error to the calling code so that it can decide how to handle it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is the ? operator in Rust?

A

A unary suffix operator which can be placed on an expression to unwrap the value on the left hand side of ? while propagating any error through an early return.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What type must a function return if it uses the ? operator?

A

Result.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

When should your code panic?

A

When it could end up in a bad state:

  1. Something not expected to happen regularly
  2. Downstream code relies on the point to be in a good state.
  3. Not a good way to encode this information in the types used.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

When should your code return a Result?

A

When failure is an expected possibility.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly