Bifalgorithm post · Computer science one · Catching Exceptions

How do you catch and handle an exception in Java?

How do you catch and handle an exception in Java? (Computer science one · Catching Exceptions) — "To catch an exception in Java you can use the standard try-ca…

Ideas in this flowchart

  • Gestion des exceptions en Java
  • Le bloc try-catch permet d’intercepter et de traiter une exception.
  • Le bloc finally peut être utilisé pour nettoyer les ressources.
  • Exemple : lire une entrée utilisateur avec Scanner.
  • La valeur saisie est convertie manuellement en entier.
  • Une entrée non numérique fait échouer l’analyse.
  • L’échec produit une NumberFormatException.
  • Le bloc catch intercepte la NumberFormatException.
  • Un message d’erreur est affiché sur la sortie d’erreur standard.
  • Le programme est ensuite quitté avec System.exit(1).
  • Le choix effectué considère cette erreur comme fatale.
  • Une autre stratégie de traitement aurait aussi pu être choisie.
Feed/

How do you catch and handle an exception in Java?

No cover

Channel

Computer science one

1 page

"To catch an exception in Java you can use the standard try-catch control block (and optionally use the finally block to clean up any resources). Let’s take, for example, the simple task of reading input from a user using Scanner and manually parsing its value into an integer. If the user enters a non-numeric value, parsing will fail and result in a NumberFormatException that we can then catch and handle. For example:\n\nScanner s = new Scanner(System.in);\n\nint n = 0;\n\ntry {\n\nString input = s.next();\n\nn = Integer.parseInt(input);\n\n} catch (NumberFormatException nfe) {\n\nSystem.err.println(\"You entered invalid data!\");\n\nSystem.exit(1);\n\n}\n\nIn this example, we’ve simply displayed an error message to the standard error output and exited the program. That is, we’ve made the design decision that this error should be fatal. We could have chosen to handle this error differently in the catch block."

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.