Skip to content

异常

运行报错 Error: non-numeric argument to binary operator. Execution halted. 。抛出异常后, R 语言中断运行,不继续。

print(1)

print(1 + 'a')

print(2)
[1] 1
Error in 1 + "a": non-numeric argument to binary operator
Calls: print
Execution halted

使用 tryCatch 处理异常。

print(1)

tryCatch(
    expr = {
        print(2)
        print(1 + 'a')
        print(3)
    },
    error = function(e) {
        print('错误')
    }
)

print(4)
[1] 1
[1] 2
[1] "错误"
[1] 4

使用 try 忽略异常。

print(1)

try({
    print(2)
    print(1 + 'a')
    print(3)
})

print(4)
[1] 1
[1] 2
Error in 1 + "a": non-numeric argument to binary operator
[1] 4

联系 math@baima.site