ptg7068951
254 HOUR 18:Handling Errors in a Program
As of Java 7, you also can handle multiple exceptions in the same catch
block by separating them with pipe (|) characters and ending the list with a
name for the exception variable. Here’s an example:
try {
value = Integer.parseInt(textValue);
catch (NumberFormatException |Arithmetic Exception exc) {
// code to handle exceptions
}
If a NumberFormatExceptionor ArithmeticExceptionis caught, it will be
assigned to the excvariable.
Listing 18.3 contains an application called NumberDividerthat takes two
integer arguments from the command-line and uses them in a division
expression.
This application must be able to deal with two potential problems in user
input:
. Nonnumeric arguments
. Division by zero
Create a new empty Java file for NumberDividerand enter the text of Listing
18.3 into the source editor.
LISTING 18.3 The Full Text of NumberDivider.java
1: public classNumberDivider {
2: public static voidmain(String[] arguments) {
3: if (arguments.length== 2) {
4: int result = 0;
5: try {
6: result = Integer.parseInt(arguments[0]) /
7: Integer.parseInt(arguments[1]);
8: System.out.println(arguments[0] + “ divided by “+
9: arguments[1] + “ equals “+ result);
10: } catch(NumberFormatException e) {
11: System.out.println(“Both arguments must be numbers.”);
12: } catch(ArithmeticException e) {
13: System.out.println(“You cannot divide by zero.”);
14: }
15: }
16: }
17: }