Re: Try...Catch


[ Follow Ups ] [ Post Followup ] [ WWWBoard for 308-203A ] [ FAQ ]

Posted by Will on September 13, 19100 at 12:51:04:

In Reply to: Try...Catch posted by Philippe Benoit on September 12, 19100 at 21:49:06:

i'll take a guess that what you have actually looks like:


try {
int number = Integer.parseInt(StdIn.readLine());
}
catch(NumberFormatException)...

doSomethingWith(number);

The problem is that number was declared as an int INSIDE
the try block, which limits its scope to the try block.
Result: "number" disappears after the end bracket.
Solution 1:

int number = 0;

try {
number = Integer.parseInt(StdIn.readLine());
}
catch(NumberFormatException)...

doSomethingWith(number)


Solution 2:

try {
int number = Integer.parseInt(StdIn.readLine());
doSomethingWith(number);
}
catch(NumberFormatException)...

NB This is a good reason to do what C forces you to do
and declare ALL local variables at the beginning of the method
body.

-Will


: I have a question..

: Lets say you want to use try..catch to pinpoint the error when someone enter a letter instead of an integer.
: I use
: try {
: int number = Integer.parseInt(StdIn.readLine());
: }
: catch(NumberFormatException)...

: yet when I compile it does not seem to aknowledge my int number.
: Can we use try-catch only with method calls??
: ex:
: try{
: liver.spleen();
: }....




Follow Ups:



Post a Followup

Name:
E-Mail:

Subject:

Comments:

Optional Link URL:
Link Title:
Optional Image URL:


[ Follow Ups ] [ Post Followup ] [ WWWBoard for 308-203A ] [ FAQ ]