Next: None. Up: More on exceptions. Previous: Multiple catch blocks.
Quite frequently you'll want to declare a variable in a try block that you want to use after the try block. Like all other statement blocks, variables declared inside the block can't be used outside the block. You might want to write the former as follows.
This won't compile, since in the expression m / n, neither m nor n are defined as variables. (We did define them in the first try block, but in the second try block we were beyond the closing brace enclosing their definition, so that definition no longer applies.)IO.println("Type two numbers to divide."); try { int m = Integer.parseInt(IO.readLine()); int n = Integer.parseInt(IO.readLine()); } catch(NumberFormatException e) { IO.println("That's not a number."); } try { IO.println(m / n); // ERROR: won't compile } catch(ArithmeticException e) { IO.println("I can't divide by zero."); }
So to make this strategy work, you'd need to declare the variables outside the block. We'll also want to give these variables an initial value, in case an exception raised inside the first block could prevent one from getting a value otherwise.
Frankly, I prefer my earlier solution with multiple catch blocks more.IO.println("Type two numbers to divide."); int m = 0; int n = 1; try { m = Integer.parseInt(IO.readLine()); n = Integer.parseInt(IO.readLine()); } catch(NumberFormatException e) { IO.println("That's not a number."); } try { IO.println(m / n); // ERROR: won't compile } catch(ArithmeticException e) { IO.println("I can't divide by zero."); }
Generally, exceptions are an important but irritating part of Java programming. You can't really ignore them, but unfortunately neither can you assume the outside world will always give you proper values with which to do your work.
Next: None. Up: More on exceptions. Previous: Variables in try clauses.