Why can't the "Statements following the structure" be used to close a file that the method has opened?
These statements will not execute if the try
block throws an
unhandled Exception
.
If the last catch block catches Exception
,
then it will catch any type of Exception
not caught
in the preceeding blocks.
Do this so the user sees a pleasant error message rather than a
confusing stack trace.
In the following excerpt,
ArithmeticException
s are caught in the first block,
and all other Exception
s in the 2nd block.
try { System.out.print("Enter the numerator: "); num = scan.nextInt(); System.out.print("Enter the divisor : "); div = scan.nextInt(); System.out.println( num + " / " + div + " is " + (num/div) + " rem " + (num%div) ); } catch (ArithmeticException ex ) { System.out.println("You can't divide " + num + " by " + div); } catch (Exception ex ) { System.out.println("Something went wrong." ); } System.out.println("Good-by" );
Where will a RunTimeException
be caught?