是否可以尝试/捕获某些东西,以检查是否抛出异常? [英] Is it OK to try/catch something just to check if an exception was thrown or not?

查看:145
本文介绍了是否可以尝试/捕获某些东西,以检查是否抛出异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个很好的方法来尝试一些无用的东西,只是为了看看这个代码是否抛出了一个特殊的异常?

当抛出异常时,我想做一些事情,没有别的。 >

Is it a good way to try something useless just to see if a particular exception is thrown by this code ?
I want to do something when the exception is thrown, and nothing otherwise.

try {  
    new BigDecimal("some string"); // This do nothing because the instance is ignored  
} catch (NumberFormatException e) {  
    return false; // OK, the string wasn't a well-formed decimal  
}  
return true;

有太多的前提条件进行测试,构造函数BigDecimal()总是检查它们,所以这似乎是最简单的方法。

There is too many preconditions to test, and the constructor BigDecimal() is always checking them all, so this seem the simplest method.

推荐答案

一般来说,这种做法应该避免。但是,由于没有实用方法 isValidBigDecimal(..),那就是要走的路。

Generally, this practice should be avoided. But since there is no utility method isValidBigDecimal(..), that's the way to go.

正如Peter Tillemans在评论中注明,将此代码放在一个名为 isValidBigDecimal(..)的实用程序中。因此,您的代码将无法确定有效性,然后您甚至可以切换到另一种方法。

As Peter Tillemans noted in the comments, place this code in a utility method called isValidBigDecimal(..). Thus your code will be agnostic of the way of determining the validity, and you can even later switch to another method.

BorisPavlović建议选择使用第3党图书馆(共同图书馆)。还有一个有用的方法,当我需要验证数字时,我使用这个方法 - NumberUtils.isNumber(..)

Boris Pavlović suggested an option to check that using a 3rd party library (commons-lang). There's one more useful method there, which I use whenever I need to verify numbers - NumberUtils.isNumber(..)

这篇关于是否可以尝试/捕获某些东西,以检查是否抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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