Exceptions don't need to stop a function ("method" in java terminology).
Most exceptions can be recovered from.
Infact, they let you write cleaner code because you aren't inserting little checks and thus the purpose of a code block is clearer. Instead you can wrap problem code in a "try catch" block and handle the exceptions at the end.
I have included a code sniplet the demonstrates forcing the user to input a valid float. If the float is invalid, the user is hassled until they do enter a correct value.
|
Code:
|
import java.io.Console;
class TestFloat {
public static void main(String[] args) {
// Get console object to read from console...
Console cons;
if ((cons = System.console()) == null){
System.out.println("Can't access console, closing program");
System.exit(1);
}
// Prompt user for a valid float, repeat until a valid float is entered
String line;
float f;
while(true) {
// Prompt user for float
System.out.print("Please enter a valid float: ");
// Read in user input as string
line = cons.readLine();
// Wrap conversion code in a try catch block to handle the exception
try {
// Try convert String to float (may throw exception)
f = Float.valueOf(line);
// Exit while loop if an exception is not thrown
break;
} catch(NumberFormatException e) {
// An exception was thrown, inform user and repeat loop
System.out.println("That is not a valid float");
}
}
// A valid float value was (eventually entered), display it
System.out.println("Float value was: " + f);
}
} |
Check out:
Lesson: Exceptions (The Java™ Tutorials > Essential Classes) for details on exceptions.
Hope this helps :-)