Try/catch 红语例外

Try/catch exceptions in Red language

我有一个带有文本字段和按钮的小型 GUI 应用程序。该按钮触发一个函数,该函数试图从文本字段中读取一个数字。如果文本字段为空或具有非数字文本,则会引发异常。

如果文本字段没有值或文本值不是有效数字,我正在尝试捕获错误:

calc: does [
    try [x: to integer! num_field/text]
    catch [ print "Could not get number"]
    print "Number read"
]

以下也不起作用:

calc: does [
    try [x: to integer! num_field/text]
    throw 123
    print "Number read"
]
catch 123 [ print "Could not get number"]

我不知道如何在这里使用 try、throw 和 catch。我试图查看 http://static.red-lang.org/red-system-specs.html 的第 10 节,但无法真正理解。

如何解决?谢谢你的帮助。

如果生成错误,

TRY 仍会传递错误,但不会触发错误,除非它是评估的最后一个值。

您可以使用以下内容:

calc: does [
    case [
        error? value: try [
            to integer! num_field/text
        ][
            ... do error handling ...
            probe make map! body-of :value
        ]

        integer? value [
            ... do successful thing ...
        ]
    ]
]

除了TRY,还有ATTEMPT,如果发生错误,它只会return NONE。不像TRY,不能分析错误对象

attempt [to integer! "Foo"]

CATCHTHROW 在 Rebol/Red 中是比错误处理程序更多的流控制功能,它们突破了它们跨越的许多堆栈级别:

catch [
    repeat x 10 [
        probe x
        if x = 3 [throw x]
    ]
]

您可以简单地使用 attempt 来捕获最终的转换错误并测试结果值:

calc: does [
    either integer? x: attempt [to-integer num_field/text][
        print "Number read"
    ][
        print "Could not get number"
    ]
]

但是,在这种特定情况下还有一个更简单的选项:

calc: does [
    either integer? x: num_field/data [
        print "Number read"
    ][
        print "Could not get number"
    ]
]

/data 方面已经包含 /text 的转换版本,或者 none 如果无法进行转换,那么您可以只 read/write 该方面的数值显示在 textfield 面孔中。

I tried to check section 10 of http://static.red-lang.org/red-system-specs.html but could not really understand.

该文档适用于 Red/System,Red 中嵌入的系统编程 DSL。 Red 语言文档位于 http://docs.red-lang.org(仍在繁重的工作中)。