Errorhandling in Java with Optional<?>

avatar

In this application, we look at how to check a user input for errors.
A number between 0 and 100 is to be entered. All other inputs are invalid in this example. The return value is an Optional<?>.
Optionals can be useful, if the return value is null.

import java.util.Scanner;
import java.util.Optional;

public class InputHandler {

    private Optional<Integer> getUserInput(){
        Scanner sc = new Scanner(System.in);
        final String rawInput = sc.nextLine();
        sc.close();

        if(rawInput == null || rawInput.length() == 0){
            return Optional.ofNullable(null);
        }

        try {
            Integer number = Integer.parseInt(rawInput);
            return number.intValue() >= 0 && number.intValue() <= 100
            ? Optional.of(number) : Optional.ofNullable(null);
        } catch ( NumberFormatException e){
            return Optional.ofNullable(null);
        }

    }

    public static void main(String[] args) {
        InputHandler h = new InputHandler();
        Optional<Integer> number = h.getUserInput();
        number.ifPresent(System.out::println);
    }
}



0
0
0.000
1 comments
avatar

Great post.

I sin of not using the try-catch statements enough in Python and not creating testing files. Would love to learn more about Java.

0
0
0.000