4 ms·
``` try { ... } catch (UserNotFoundException e) { // handle ... } ``` This is just bikeshedding, because the equivalent code
by anon-3988 3y ago
```
try {
...
}
catch (UserNotFoundException e) {
// handle ...
}
```
This is just bikeshedding, because the equivalent code in Rust would be. For example, if there's multiple lines in the try block, who exactly returned this error? Are there other errors I didn't handle? Are there unexpected error that I forgot to check. For example, the "get" function of arrays in many languages usually always return T. But this is actually a lie because the array might be empty. So by right, it should return Option<T>. But exception based programming have basically created this illusion that its infallible. How many people check their array accesses?
```
match value {
Ok(ok)=> {...}
Err(UserNotFoundException(e)) = { handle }
e => return e
}
```
Which does look more complicated, but it scales way way better when you have multiple errors
> But it is pretty bad for truly exceptional cases (which are unlikely to be handled anyway).
But why should a language be designed for exceptional cases? Errors are not exceptional at all. In the above code, the actual code will actually look like this
```
let rows = db.get_rows(query)?; // returns Result<Vec<DbRow>, E1>
let first_row = rows.first()?; // returns Option<DbRow>
let user = first_row.to_user()?; // returns Result<User, E2>
return user
```
Exception-based language will have the same looking code, but then imagine what would happen if you try to figure out which functions return what. You have no other recourse other than to dig into the source code to find all the unchecked exceptions that it can throw.
Another example, how would an exception language write this code to get multiple rows from the db and map each row to its respective user.
```
// get_rows and to_user both can fail
let users :Vec<User> = db.get_rows(query)?.map(|r|r.to_user()).collect::<Result<_,_>()?;
```