Next: None. Up: More on exceptions. Previous: Multiple catch blocks.


Variables in try clauses

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.

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.");
}
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.)

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.

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.");
}
Frankly, I prefer my earlier solution with multiple catch blocks more.

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.

Exercise


Next: None. Up: More on exceptions. Previous: Variables in try clauses.