3 ms·
We use panics for logic errors. This is an important distinction. We will never throw if a file couldn't open, or if a string couldn't parse, because these are
by Gankro 11y ago
We use panics for logic errors. This is an important distinction. We will never throw if a file couldn't open, or if a string couldn't parse, because these are expected errors that you should explicitly handle.
Catching panics should never be part of an application's normal control flow in Rust, unlike e.g. Java and C#. These languages use exceptions to indicate any error condition, and therefore writing correct error handling code requires try/catch.
Exceptions in Rust are used as a "soft abort". A real abort tears down the entire process, and the OS handles releasing all associated resources. But if you're writing a program that has logical tasks that resemble processes, the OS can't individually tear those down for you. When an exception (panic) is thrown in Rust, the task has hit a situation that cannot be recovered, and tears itself down so the rest of the application can reclaim the resources.
The places in Rust where exceptions are thrown are usually places where the programmer has chosen not to handle a logic error -- usually indexing out of bounds, integer overflows (sometimes), or forcing an optional value. Things that would be RuntimeExceptions (unchecked exceptions) in Java.