how can i rewrite the following code using try and catch statements,catching any exceptions that might be thrown
for (j=0; j<limit; j++)
{
x=Integer.parseInt(keyboard.readLine());
y[j]=1/x;
}
how can i rewrite the following code using try and catch statements,catching any exceptions that might be thrown
for (j=0; j<limit; j++)
{
x=Integer.parseInt(keyboard.readLine());
y[j]=1/x;
}
That depends if you want the loop to end if there is an error, or you want it to continue...
# loop continues on errors
for ..
try
dostuff
catch something
fix
vs
# loop ends on errors
try
for ..
dostuff
catch something
..
Java like pseudocode
for (j=0; j<limit; j++)
{
try{
x=Integer.parseInt(keyboard.readLine());
y[j]=1/x;
}
catch(some_exception_not_gonna_say_which_one sengswo){
//handle exception
}
}
I am guessing that you want a certain number of integers from the user. A while loop will probably make more sense here than a for loop as you will want to loop until you have the correct number of inputs form the user.
Also, in most cases y[j] is going to hold a zero, as 1 / x is 0 for x > 1. use 1.0/x
instead to get floating point math and not integer math.
while j < limit
try
// parse number
// store number
// increment j
catch
// inform user of error
end while
Here is how you can do it in Java. It's better to surround the loop with the try/catch instead of placing the try/catch inside the loop when possible for performance reasons. However, if you want the loop to continue when an error occurs, then you will need to place the try/catch inside the loop.
Loop inside try/catch:
try {
for (j=0; j<limit; j++)
{
x=Integer.parseInt(keyboard.readLine());
y[j]=1/x;
}
} catch(Exception e) {
e.printStackTrace();
}
Loop outside try/catch:
for (j=0; j<limit; j++) {
try {
x=Integer.parseInt(keyboard.readLine());
y[j]=1/x;
} catch(Exception e) {
e.printStackTrace();
}
}
The real question is what do you want to do with the exception (i.e. why even bother catching it)? I would think that you would want to verify or cleanse whatever keyboard input you're getting (IMO a programmer should never trust a user's input), so you would want to ensure that the input is a digit (hint: regex).
There are basically three questions that you need to ask in this scenario: can I recover from this exception, should an exception halt execution, or should I ignore the exception (eat it, and continue to the next number)?