简体   繁体   中英

How to work with try-catch in JavaFX?

I'm doing this project as a school project and one of the compulsory things is to catch something that user doesn't do right.

I have this list of cards where user can add or remove cards. I wanted to use a try-catch on the removal part - if the user tries to remove one of the default cards (not user input card) it will display an error.

I would like to do is notify user with a label that it is impossible for him to remove it. It would be simple to do with if-else but how to do it with try-catch?

eemalda.setOnAction(new EventHandler<ActionEvent>() {
    public void handle(final ActionEvent event) {
        if (((Kaardid) kaardid2.get(kaardid2.size() - 1))
                .getKaardi_nimi().contains("Ei pea jooma see ring")) { // after this if should be try-catch
            viimane_kaart.setText("Viimane sisestatud kaart on Baila originaalkaart");
        } else { // after this comes the other stuff program does
            kaardid2.remove(kaardid2.get(kaardid2.size() - 1));
            seadetemant.setVisible(false);
        }
    }
});

Using try - catch in java is the same no matter which framework or packages you use. The same try - catch statement

try{
 // your code
 }

catch(Exception e){
 // your code
}

I don't advise using a try-catch statement for the situation described in your question.

See also Brian Roach's answer to: Using Exceptions to validate inputs

Exceptions should be used for exceptional conditions ; things you don't expect to happen. Validating input isn't very exceptional.

The best way to handle invalid input in UIs is to:

  1. Prevent situations in which invalid input can occur.
  2. If prevention is not possible, provide immediate feedback on invalid input.

For your sample situation, rather than allowing the user to select an unremovable card, attempt an operation to remove it and then telling them that they can't remove it, you could either:

  1. Not allow them to select unremovable cards in the first place OR
  2. If a unremovable card is selected, disable the button or function for card removal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM