J
J
Jake Taylor2021-04-29 15:44:41
Java
Jake Taylor, 2021-04-29 15:44:41

What is the correct way: check for null through if or throw an exception in try-catch in Java?

There is a create method for creating an instance of the CustomArray class , which takes an array of int primitives as an argument.
A custom exception class, ArrayException , has also been created .
One of the conditions for the method should be: -
checking the method argument for null ;
- checking method argument for zero size.

From the point of view of the correct implementation of checking for null a method argument, how to properly implement a method by checking the argument for null through an if condition or throwing an exception in a try-catch construct ?

The method itself:

public CustomArray create(int[] numbers) throws ArrayException {
}


Option using if:
public CustomArray create(int[] numbers) throws ArrayException {
        if(numbers.length == 0) {
            throw new ArrayException("Array is empty!");
        } else if (numbers == null) {
            throw new ArrayException("An empty argument passed!");
        }
    }


Try-catch example:
public CustomArray create(int[] numbers) throws ArrayException {
        CustomArray customArray;

        try {
            customArray = new CustomArray(numbers);
        } catch (NullPointerException ex) {
            throw new ArrayException("Null pointer!");
        } 
        
        return customArray;
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2021-04-29
@n199a

Exceptions are not needed.

public Optional<CustomArray> create(int[] numbers) {
    return Optional.ofNullable(numbers)
        .filter(a -> a.length > 0)
        .map(CustomArray::new);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question