Catching Exceptions
try
, catch
, and finally
(optional) blocks.
try
- attempts to complete the code here. If an exception occurs, jumps to corresponding catch
catch
- need to name the exception type you want to catch
finally
- always executes, whether try block completed normally, one of the catch blocks caught an exception, or if an exception was thrown that was not caught by any of the catch blocks
- A contrived example (wouldn't normally catch AIOOBE or divide by 0, but avoid it in the first place):
int n = ... //try: 2 or 0 or 4
int[] nums = {0, 2, 4, 6};
try {
int x = 15 / nums[n];
System.out.println(x);
}catch (ArithmeticException e) {
System.out.println("Can't divide by 0.");
}finally {
System.out.println("Done.");
}
System.out.println("Goodbye.");
User Input with Scanner (3/3)
//gets a positive integer from the user
Scanner keybd = new Scanner(System.in);
int input = 0;
while (input <= 0) {
try {
System.out.print("Enter a positive integer: ");
input = keybd.nextInt();
if (input <= 0) {
System.out.println("That is not a positive integer.");
}
}catch (InputMismatchException e) {
System.out.println("That is not even an integer!");
keybd.nextLine(); //important: clears the bad input from the input stream
}
}
System.out.println("You entered: " + input);