Yes.
throw
Statement
Here is another version of the program.
This time, the try
block detects potential division by zero in an if
statement and throw
s
an Exception
.
// Version 3 // try { System.out.print("Enter the numerator: "); num = scan.nextInt(); System.out.print("Enter the divisor : "); div = scan.nextInt(); if ( div == 0 ) throw new ArithmeticException() System.out.println( num + " / " + div + " is " + (num/div) + " rem " + (num%div) ); } catch (InputMismatchException ex ) { System.out.println("You entered bad data." ); System.out.println("Run the program again." ); } catch (ArithmeticException ex ) { System.out.println("You can't divide " + num + " by " + div); } }
When a zero divisor is detected, the new
operator constructs an Exception
object which
is thrown, and is then caught by a catch
block.
If the throw
is performed, the rest of the try
block will not be executed.
This version of the program is awkward. There is no advantage here in explicitly throwing an Exception
.
Version 2 is the best version of these three.
(Other versions are possible. If you are not careful, combining exception handling with logic can produce a real mess.)
Here is a program fragment. What does it print?
int[] data = { 3, 2, -3, 5 }; int sum = 0; int avg; try { for ( int j=0; j<=4; j++ ) sum += data[j]; avg = sum/0 ; } catch ( ArrayIndexOutOfBoundsException ex ) { System.out.println("Off by one." ); } catch ( RuntimeException ex ) { System.out.println("Runtime Problem." ); } catch ( Exception ex ) { System.out.println("Exception" ); } System.out.println("sum is" + sum );