python中的try except与R语言中的tryCatch异常解决
作者:Kanny广小隶 时间:2021-10-22 02:24:48
1. 起因
当我们需要写一个非常非常长的循环时,通常在某个循环如果出现error,那么整个代码后面的循环就不能进行。
这时候试想,如果你在服务器上挂一个要跑很久的循环(并行),亦或是需要在自己电脑上挂一晚上跑东西,可能刚点完运行,美滋滋地 * 后,程序突然出现问题。这时第二天满怀期待地点亮屏幕,发现是一个大大的红红的ERROR
时,估计头发或许又会稀疏了不少。
于是这时候就会想,能不能在跑的时候,如果程序出现错误,那么我们直接绕开这些问题,进行下一次循环。
其实这种问题在Python
与R
中,都有相应的解决方法。
2. Python中的try/except
首先贴上官方说明文档:
英文文档:https://docs.python.org/3/tutorial/errors.html
中文文档:https://docspy3zh.readthedocs.io/en/lates t/tutorial/errors.html
这里我们仿造文档中间的例子进行构造自己的例子,具体如下述代码所示。
def divide(x, y):
try:
result = x / y
except ZeroDivisionError:
print("division by zero!")
except:
print('unknown error!')
else:
print("result is", result)
finally:
print("executing finally clause")
这里解释一下程序逻辑:首先运行try
,如果:
不报错,就会跳到else
,最后到final
分母为0的错误,会跳到except ZeroDivisionError
,然后直接忽略else
到最后的finally
其他类型的错误,会忽略exc
ept ZeroDivisionError
,然后到except
,接着再忽略else
到最后的finally
也就是说无论如何,finally
都是会运行的。
下面我们验证三种输入:
1)情形一
输入:
divide(2, 1)
输出:
result is 2.0
executing finally clause
2)情形二
输入:
divide(2, 0)
输出:
division by zero!
executing finally clause
3)情形三
divide("2", "1")
输出:
error!
executing finally clause
3. R中的tryCatch
同样的,在R
中的tryCatch
函数也是同样解决类似的问题。
可参考官方说明文档:trycatch: Evaluates an expression with the possibility to catch exceptions (DEPRECATED)
然后运行上面类似的程序,来看看用法
divide <- function(x, y) {
result <- tryCatch({
x / y
}, warning = function(war) {
cat("warning!", war, "\n")
}, error = function(err) {
cat("error!", err, "\n")
}, finally = {
print("executing finally clause")
})
return(result)
}
这里需要格外注意的是,tryCatch
后面是要加上小括号和大括号的。另外我加上了err
这个对象,相当于会输出报错信息。
下面为运行结果:
1)情形一
输入:
divide(1, 2)
输出:
[1] "executing finally clause"
[1] 0.5
我是先finally
,再return
,所以会是上述的输出结果。
2)情形二
输入:
divide(1, 0)
输出:
[1] "executing finally clause"
[1] Inf
注意,R会输出Inf
,这点与Python不同。
3)情形三
输入:
divide(1, '0')
输出:
error!
Error in cat("error!", err, "\n") :
argument 2 (type 'list') cannot be handled by 'cat'
[1] "executing finally clause"
补充
最后如果我们如果想要在R
中忽略一些可能报错的代码时(不需要输出任何报错信息),直接使用try()
即可。
来源:https://kanny.blog.csdn.net/article/details/84667843
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
重新编译PLSQL中的无效对象或者指定的对象 的方法
JavaScript Dom编程:介绍学习书籍
仿天涯底部固定漂浮导航,无JS纯CSS定义
还不知道Anaconda是什么?读这一篇文章就够了
![](https://img.aspxhome.com/file/2023/9/114639_0s.png)
python解析中国天气网的天气数据
Python中defaultdict与dict的差异详情
不归路系列:Python入门之旅-一定要注意缩进!!!(推荐)
![](https://img.aspxhome.com/file/2023/5/78735_0s.png)
thinkPHP引入类的方法详解
![](https://img.aspxhome.com/file/2023/1/122491_0s.png)
关于Theano和Tensorflow多GPU使用问题
python django框架中使用FastDFS分布式文件系统的安装方法
![](https://img.aspxhome.com/file/2023/2/66462_0s.jpg)
Firefox插件推荐:CSS Usage
![](https://img.aspxhome.com/file/UploadPic/200910/26/cssusage-70s.jpg)
使用 JSON 进行数据传输
PHP数组中头部和尾部添加元素的方法(array_unshift,array_push)
![](https://img.aspxhome.com/file/2023/2/55472_0s.png)
《JavaScript语言精粹》译者序及样章试读
JavaScript 中的 this 绑定规则详解
![](https://img.aspxhome.com/file/2023/8/132648_0s.jpg)
Go语言工程实践单元测试基准测试示例详解
![](https://img.aspxhome.com/file/2023/0/107380_0s.jpg)
如何利用JavaScript编写更好的条件语句详解
SQL2005重新生成索引的的存储过程 sp_rebuild_index <font color=red>原创</font>
原生JS实现九宫格抽奖
python中Requests发送json格式的post请求方法
![](https://img.aspxhome.com/file/2023/3/66773_0s.png)