Exceptions/Catch an exception thrown in a nested call: Difference between revisions

Added Rust
(Added Rust)
Line 2,611:
from exception.rb:2:in `foo'
from exception.rb:23:in `<main>'</pre>
 
=={{header|Rust}}==
Rust has panics, which are similar to exceptions in that they default to unwinding the stack and the unwinding can be caught. However, panics can be configured to simply abort the program and thus cannot be guaranteed to be catchable. Panics should only be used for situations which are truly unexpected. It is prefered to return an Option or Result when a function can fail. <code>Result<T, U></code> is an enum (or sum type) with variants <code>Ok(T)</code> and <code>Err(U)</code>, representing a success value or failure value. <code>main</code> can return a Result, in which case the debug representation of the error will be shown.
<lang Rust>#[derive(Debug)]
enum U {
U0(i32),
U1(String),
}
 
fn baz(i: u8) -> Result<(), U> {
match i {
0 => Err(U::U0(42)),
1 => Err(U::U1("This will be returned from main".into())),
_ => Ok(()),
}
}
 
fn bar(i: u8) -> Result<(), U> {
baz(i)
}
 
fn foo() -> Result<(), U> {
for i in 0..2 {
match bar(i) {
Ok(()) => {},
Err(U::U0(n)) => eprintln!("Caught U0 in foo: {}", n),
Err(e) => return Err(e),
}
}
Ok(())
}
 
fn main() -> Result<(), U> {
foo()
}</lang>
{{out}}
<pre>Caught U0 in foo: 42
Error: U1("This will be returned from main")</pre>
 
=={{header|Scala}}==
Anonymous user