3 ms·
I'm confused — how would one use exceptions if not for control flow?
by skitter 3y ago
I'm confused — how would one use exceptions if not for control flow?
- tialaramex 3y agoIn general exceptions are error handling, for "exceptional" situations. For example suppose we're supposed to ensure the water flow is at least X litres per second, but now X is NaN, that's nonsense, raise an exception. You are correct that unlike a Result sum type, or an error code, or numerous other error solutions the exceptions inherently also change control flow. In Python though it's usual to (ab)use exceptions for other flows, for example to indicate that we're done, lets just throw a Done exception. The distinction is why Rust reifies control flow as the ControlFlow type, https://doc.rust-lang.org/core/ops/enum.ControlFlow.html https://doc.rust-lang.org/core/ops/enum.ControlFlow.html -- so we have shared vocabulary to distinguish "This failed w/ error X" Result::Err(X) from "We should stop now, result Y" ControlFlow::Break(Y) even though sometimes it's true that we're stopping because of an error so we end up transforming Result::Err(X) into ControlFlow::Break(X). Doing that transformation is what the Try trait, the operator ? does today it calls Try::branch(result) and if that's ControlFlow::Break(X) your function exits with X, if it's ControlFlow::Continue(C) then the operator's result is C.