The catch{}
blocks are in a correct order,
because ArithmeticException
is not
an ancestor nor a descendant of NumberFormatException
.
The other order of the two blocks would also work.
In the example program,
the try{}
block
might throw
(1) an IOException
,
(2) a NumberFormatException
,
or
(3) an ArithmeticException
.
public static void main ( String[] a ) throws IOException . . . . try { System.out.println("Enter the numerator:"); inData = stdin.readLine(); num = Integer.parseInt( inData ); System.out.println("Enter the divisor:"); inData = stdin.readLine(); div = Integer.parseInt( inData ); System.out.println( num + " / " + div + " is " + (num/div) ); } catch (NumberFormatException ex ) { . . . } catch (ArithmeticException ex ) { . . . } }
An IOException
might occur in either readLine()
statement.
There is no catch{}
block for this type of exception,
so the method has to say throws IOException
.
A NumberFormatException
might occur in either call to
parseInt()
.
The first catch{}
block is for this type of exception.
It will catch exceptions thrown from either parseInt()
.
An ArithmeticException
might occur if the user enters
data that can't be used in an integer division.
The second a catch{}
block is for this type of exception.