For checked Exceptions, a method must either declare that it throws the Exception,
or it must catch the Exception.
Exceptions not Caughtimport java.util.Scanner; import java.io.*; public class EchoSquareDisk { public static void main (String[] args) throws IOException { File file = new File("myData.txt"); // create a File object Scanner scan = new Scanner( file ); // connect a Scanner to the file int num, square; num = scan.nextInt(); square = num * num ; System.out.println("The square of " + num + " is " + square); scan.close(); } }
You have seen this program before (in chapter 72.)
It reads its data from
myData.txt, a text file.
The first line contains an integer in character format.
The constructor new Scanner( file )
might throw a FileNotFoundException.
This program declares
throws IOException
one of the two options for checked exceptions.
If the first line of the input file contains a group of characters that cannot be
converted into an int then scan.nextInt()
might throw a
InputMismatchException
However, InputMismatchException is a decendant class of RuntimeException,
an unchecked Exception
so the method does not have to catch it nor throw it.
Could the program catch both of the Exception types that might arise?