1

Here is the code snippet :

myObject[] array = Arrays.copyOf(original, original.length, myObject[].class);

Is it okay to catch exception instead of checking original against null?

Tamir Abutbul
  • 7,301
  • 7
  • 25
  • 53
VenkatN
  • 13
  • 2
  • I would like to ask the question, why you want to do this? Regarding your answer the following answers may help: https://stackoverflow.com/questions/2586290/is-catching-a-null-pointer-exception-a-code-smell?rq=1 – Denis Lukenich Jun 05 '19 at 20:22
  • Why don't you want an exception? Exceptions are healthy; they tell you there's a bug and where to look for it. – Louis Wasserman Jun 05 '19 at 20:25
  • Also: https://stackoverflow.com/questions/9758457/try-catch-vs-null-check-in-java – Marvin Jun 05 '19 at 20:29

3 Answers3

1

Checking for null is more performant than throwing an exception.

Michael
  • 34,873
  • 17
  • 75
  • 109
0

It's generally not a good idea to catch exceptions unless your expecting that a particular type of exception might occur. (e.g. email already in system might throw a validation exception, or if data is not found you might get a BadRequest exception)

When applicable, like it seems likely in your snippet, it would be better to do a null check and direct to two different flows depending on what is found. Alternatively, you could instantiate a new array if none is found.

0

Checking If (value == null) advantages against exception block

  1. Better Performance
  2. More clean
  3. Less code
Samet ÖZTOPRAK
  • 3,112
  • 3
  • 32
  • 33