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;
There is too many preconditions to test, and the constructor BigDecimal() is always checking them all, so this seem the simplest method.
With a try catch, you can handle an exception that may include logging, retrying failing code, or gracefully terminating the application. Without a try catch, you run the risk of encountering unhandled exceptions. Try catch statements aren't free in that they come with performance overhead.
Hi Shola, yes you can use try / catch without a throw. Nevertheless, as try / catch only makes sense if an exception can be thrown, this code would not make much sense.
Some exception can not be catch(Exception) catched. Below excecption in mono on linux, should catch without parameter. Otherwise runtime will ignore catch(Exception) statment.
What happens if an exception is not caught? If an exception is not caught (with a catch block), the runtime system will abort the program (i.e. crash) and an exception message will print to the console. The message typically includes: name of exception type.
Generally, this practice should be avoided. But since there is no utility method isValidBigDecimal(..)
, that's the way to go.
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.
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(..)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With