Yes.
Exception
Handlingimport java.util.*; import java.io.*; public class EchoSquareException { public static void main (String[] args) { int num, square; Scanner scan = null; try { File file = new File("myData.txt"); // create a File object scan = new Scanner( file ); // connect a Scanner to the file num = scan.nextInt(); // read and convert the first token square = num * num ; System.out.println("The square of " + num + " is " + square); } catch ( IOException iox ) { System.out.println("Error opening the file"); } catch ( InputMismatchException imx ) { System.out.println("Bad data in the file"); } if ( scan != null ) scan.close(); System.out.println("Good-bye"); } }
This program catches both Exception
types that might arise.
If both the creation of the Scanner
and the execution of scan.nextInt()
worked,
then the square of the number is printed out and neither catch
block is executed.
At the end of the method, the input stream is closed if is was opened successfully (and therefor not null
).
Always close a stream when it is no longer needed, but first check that it is open.
Here are some sample runs of the program:
C:\JavaSource> java EchoSquareException The square of 13 is 169 Good-bye C:\JavaSource> java EchoSquareException Bad data in the file Good-bye C:\JavaSource> java EchoSquareException Error opening the file Good-bye C:\JavaSource>
(Review: ) If a method has a try
block, must there be a catch
block?