304? 7. [15] Exceptions Consider the following code 7/Some imports excluded for
ID: 3904839 • Letter: 3
Question
304?
7. [15] Exceptions Consider the following code 7/Some imports excluded for brevity public class WhichExcepl ( public static void main(Stringl] args) ( System.out.printinFile: Inputl.dat+sumOtFile Ioputt dat) System.out.printin"File: Inputa dat sumOfilecInputz da public static int sumoFile(String filename) int theSum try f o Scanner fScanner new Scanner (new File(filename)) int[I values findAlllntegers(fScanner); for (int v: values) ( theSum + v ) catch (FileNotFoundException e) t System.out.println"Bad Filename"): catch (InputMismatchException e) ( System.out.printin"Bad input catch (Exception e) ( System.out.printin("Unknown Exception!): return theSum; public static int findAllintegers(Scanner file) throws IOException ( inté return Ints # new int [25]; int nextEntry 0; try f while (file.hasNext0) ( returnints(nextEntry] = file.nextInt(); catch (InputMismatchException e) ( System.out.println("Wrong input type"); throw new IOExceptionO; return returnints; What does this code print if Input1.dat contains: 10 20 30 next And if the file Input2.dat does not exist?Explanation / Answer
The output of the above given program will result in like,
Wrong input type
Unknown Exception
File: Input1.dat 0
Bad Filename
File: Input2.dat 0
Explanation:
The output line Wrong input type, will be generated because the InputMismatchException is catched in the method findAllIntegers(), because of the file content of 'next',
also a new IOException is throwed while returning to the calling method that is sumOfFile(),
The throwed IOException, is now catched as Unknown Exception by the sumOfFile() method as a default catch, thus resultting in the output of Unknown Exception.
theSum, which is containing 0, is then returned and thus the print operation for input1.dat file, in the main() method outputs,
File: Input1.dat 0
As, Input2.dat file does not exist, a FIleNotFoundException is throwed in the sumOfFile() method thus resultting in
Bad Filename
with a return of theSum = 0, that calls for the print method for input2.dat, in main method
File: Input2.dat 0,
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.