Russ tries to help us out when it comes to handling errors in our programs.
Firstly, Russ is going to group errors into two categories recoverable and unrecoverable.
Recoverable errors are going to rely on the result type, and then unrecoverable errors are going to
use the panic macro.
So let's start off by looking at the panic macro.
The panic macro is going to terminate the current thread.
So let's terminate our main thread and we'll say panicked here.
And now we'll run this and we can see that it says thread Maine panicked at panicked here which was
our error message or our panic message.
I should say one example that would cause a panic to occur is if we try to perform an out of bounds
access on array.
So let's look at that real quick.
So let's create a vector
and let's just put in a value of one.
And now let's say that we want to access index ten at the vector for whatever reason.
So obviously the ID does not signal signal that this is an error.
But when we run this.
It says thread main panicked at index out of bounds, which is right here.
The length is one, but the index is ten.
So it was able to give us a good error message.
But again, this.
Index out of balance caused a panic.
So now we see that it says note run with rest underscore backtrace equals one environment variable to
display a backtrace.
So let's do that real quick and I'm doing this on Windows.
So for me to set the environment variable, I.
Run this command right here to set Russ back trace equal to one.
So now that I have it and we run cargo run again, we see that I have the backtrace printed out.
The Backtrace is basically just going to give us a list of all the functions in a recursive order.
Leading up to our air and to the program.
Unwinding.
So unwinding is the default behavior for handling a panic.
The first thing we get is an error message printed to the terminal in this case.
Then the stack starts to unwind.
During this process, temporary values, local variables, current function arguments, etc. are all
dropped in the reverse order they were created.
Once the current function is cleaned up, it moves on to whoever called the function that panicked and
performs the same unwinding process.
Then eventually, after all, the unwinding is completed, the thread exits.
If the panicking thread was the main thread, the whole process exits, which is what we did in this
case.
There is another behavior that panicking can have and that is called an abort in the event of an abort.
Unwinding does not happen.
For example, imagine we called a customized drop method during the unwinding process, but this drop
method also panics.
This would be considered fatal and causes the whole process to stop.
And that's really all there is to it, to panics.
So now that we know how panics work, let's look at air handling that we can manage with recoverable
errors.