Using R — Easier Error Handling with try()

本文介绍R语言中使用try()函数进行错误处理的方法,并通过示例展示如何捕获和处理警告及错误消息。
This entry is part 5 of 14 in the series Using R

In a previous post we looked at error handling in R with the tryCatch() function and how this could be used to write Java style try-catch-finally blocks. This time we’ll look at what can be done with the try() function and how we can easily process warning and error messages to take appropriate action when something goes wrong.

The try() function is really just a simplified interface to tryCatch(). To see how try() calls tryCatch() you can examine the guts of the try() function by typing try [without parens] at the R prompt but you may not like what you see. For those of us outside the R core development team, this is not a good place to start. The ?try documentation is much better and has a useful example showing how try() can be used to generate simulated results, ignoring those that generated errors. But this documentation doesn’t address the kind of error handling one needs for ‘business logic’ where different actions are taken depending on the kind of error issued.

For this post, we will more generally explore how try() can be used and how warning and error messages can be processed using geterrmessage() and grepl(). The important things to remember about these functions are:

  • try() only ignores warnings, not errors
  • options(warn=2) turns warnings into errors
  • geterrmessage() returns the character string associated with the last error
  • grepl(pattern, string) returns TRUE if ‘pattern’ if found within ‘string’, FALSE otherwise

With just these functions we have everything we need to write very simple constructs that can evaluate a function and handle both errors and warnings. The test script at the end of this post demonstrates how messages and errors can be generated within a function and then trapped and processed by a calling function, potentially generating new errors that could be passed upstream. Just copy and paste the script at the end, make it executable and try it out with the these shell commands:

And here is the script.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值