V: Error recovery

Created on 29 Jan 2020  路  2Comments  路  Source: vlang/v

Can there be a method to recover from an error ? Not all errors should exit the function (with return)
Perhaps something like:

```
f := os.open('some file') or {
recover os.open('some other file') // which assignes f
}

Feature Request

Most helpful comment

@cthackers Some existing ways of achieving this are:

A) use alternative optional syntax

if f1 := os.open('a.txt') {
    // do something with f1 (a.txt)
}
else {
        println('could not open a.txt')
    if f1 := os.open('b.txt') {
        // do something with f1 (b.txt)
    } else {
        println('could not open a.txt or b.txt')
    }
}

B) provide a default value for the optional

mut f2 := os.open('a.txt') or {
        println('could not open a.txt')
    os.File{} // default
}
if !f2.opened {
    f2 = os.open('b.txt') or {
        panic('could not open a.txt or b.txt')
    }
}
// do something with f2 (a.txt or b.txt)

In this second example, if the last of the statements inside the or block has the same type as the optional function return type, it will be used as a default value in case of an error (in this case os.File{}).

All 2 comments

@cthackers Some existing ways of achieving this are:

A) use alternative optional syntax

if f1 := os.open('a.txt') {
    // do something with f1 (a.txt)
}
else {
        println('could not open a.txt')
    if f1 := os.open('b.txt') {
        // do something with f1 (b.txt)
    } else {
        println('could not open a.txt or b.txt')
    }
}

B) provide a default value for the optional

mut f2 := os.open('a.txt') or {
        println('could not open a.txt')
    os.File{} // default
}
if !f2.opened {
    f2 = os.open('b.txt') or {
        panic('could not open a.txt or b.txt')
    }
}
// do something with f2 (a.txt or b.txt)

In this second example, if the last of the statements inside the or block has the same type as the optional function return type, it will be used as a default value in case of an error (in this case os.File{}).

This confusion/question seems to originate from the (IMHO unfortunate) dualism.

The solutions @joe-conigliaro outlined above should be preferred nearly everywhere and panic()s actually rather discouraged.

Was this page helpful?
0 / 5 - 0 ratings