Home > Mobile >  How to create try{ }catch(){ } block with custom message?
How to create try{ }catch(){ } block with custom message?

Time:11-02

I have method looks like:

public Optional<UserDTO> getUser(String id) {
    if (userRepository.findById(Integer.valueOf(id)).isPresent()) {
        return userRepository.findById(Integer.parseInt(id))
                .map(this::map);
    }
    throw new UserNotFoundException("User wasn't found");
}

But I want to make it with try{} catch(){} blocks, I've tried to make it like this:


public Optional<UserDTO> getUser(String id) {
    try {
        userRepository.findById(Integer.valueOf(id)).isPresent();
        return userRepository.findById(Integer.parseInt(id))
                .map(this::map);
    } catch (UserNotFoundException userNotFoundException){
        var message = "User wasn't found";
        System.out.println(message);
    }
}

but it had't thrown an exception in the case of wrong id and shown a mistake with an absence of return block.

Could you help me to find the possible solution?

CodePudding user response:

It will not throw an exception because there are none to throw in your code, you can do what you want with one line like so

userRepository.findById(Integer.valueOf(id)).orElseThrow(() -> new UserNotFoundException("User wasn't found"));

CodePudding user response:

You forgot the if part.

public Optional<UserDTO> getUser(String id) {
try {
    if(userRepository.findById(Integer.valueOf(id)).isPresent()){
      return userRepository.findById(Integer.parseInt(id))
            .map(this::map);
    } else {
      throw new UserNotFoundException();
    }
} catch (UserNotFoundException userNotFoundException){
    var message = "User wasn't found";
    System.out.println(message);
}

}

  • Related