Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it OK to try/catch something just to check if an exception was thrown or not?

Tags:

java

exception

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.

like image 868
Clément Avatar asked Sep 10 '10 11:09

Clément


People also ask

When should you not use try catch?

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.

Can we use try catch without throw?

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.

Can we use catch () without passing arguments in it?

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 thrown but not caught?

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.


1 Answers

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(..)

like image 161
Bozho Avatar answered Sep 21 '22 00:09

Bozho