什么时候可以捕获RuntimeException [英] When is it OK to catch a RuntimeException

查看:120
本文介绍了什么时候可以捕获RuntimeException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在最近的一个项目中,我建议在测试工具代码中捕获一个RuntimeException,并记录它。代码处理来自数据库的一系列输入,并且我不希望测试由于任何一个输入(Null值,非法参数等)的失败而停止。不用说,我的建议引发了热烈的讨论。



是否接受任何类型的RuntimeException?如果是的话,其他可以捕获RuntimeExceptions的场景是什么?

解决方案

你捕获 RuntimeException 因为你捕捉到任何异常的原因:你打算用它做一些事情。也许你可以纠正任何导致异常的事情。也许你只想重新抛出一个不同的异常类型。



捕获和忽略任何异常都是非常糟糕的做法。 / p>

On a recent project I recommended catching a RuntimeException within a test harness code and logging it. The code processes a series of inputs from a database, and I do not want the test to stop due to failure of any one input (Null values, Illegal arguments, etc.). Needless to say, my suggestion triggered a passionate discussion.

Is catching any kind of RuntimeException acceptable? If yes, what are other scenarios where it is OK to catch RuntimeExceptions?

解决方案

You catch RuntimeException for the same reason that you catch any exception: You plan to do something with it. Perhaps you can correct whatever caused the exception. Perhaps you simply want to re-throw with a different exception type.

Catching and ignoring any exception, however, is extremely bad practice.

这篇关于什么时候可以捕获RuntimeException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆