Concept
How do you catch and handle an exception in Java?
ComputerScienceOne / Catching Exceptions
"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."
Related Ideas
- What is a checked exception in Java?ComputerScienceOne · Checked Exceptions
- Why should the most specific exception types be caught before general ones?ComputerScienceOne · Throwing Exceptions
- How does try-with-resources simplify closing file input resources?ComputerScienceOne · File Input
- How can a Scanner read input from a file?ComputerScienceOne · File Input
- How do you read numeric input from a user in Java with Scanner?ComputerScienceOne · Converting Units
- How can you manually throw an exception in Java?ComputerScienceOne · Creating Custom Exceptions
- How do you create a custom exception in Java?ComputerScienceOne · Throwing Exceptions
- How do you catch exceptions in PHP?ComputerScienceOne · Catching Exceptions