Question

3. Handling exceptions with a finally clause a. Download the following file from the class website:...

3. Handling exceptions with a finally clause

a. Download the following file from the class website: TestFinally.java

b. Examine the code to determine what it does.

c. Compile the code and notice the error.

d. Modify TestFinally.java to handle the exception following these instructions (and those embedded in the code):

i. Embedded in the code is a note showing the location for the try statement.

ii. The first line of the catch block should look like this: catch(IOException e) {

iii. Display a meaningful error message to indicate the error that has occurred and include the following statement in your catch clause: System.out.println("The exception is: " + e);

iv. Even when an error occurs in a method, there may be clean - up activities that are required before the method or program terminates. In this case, any open files should be closed prior to terminating the program.

v. Include a finally block that closes the files using notes 4 and 5 in the code that show where to place the beginning and end of the block.

vi. You will need to add a try - catch block inside the finally block to handle any IOExceptions associated with the file close operation.

e. Test your code. When it is working, you will generate another type of exception.

f. Add a second catch clause inside the finally block with a meaningful message to handle this new exception

TestFinally.java is as follows:

import java.io.*;

public class TestFinally{

public static void main(String[] args){

FileInputStream in1 = null;

FileInputStream in2 = null;

//Open an existing file trycatch.txt

File inputFile1 = new File("trycatch.txt");

//Open a non-existent file nosuchfile.abc

File inputFile2 = new File("nosuchfile.abc");

//1. Add the try statement here

//Get file handlers in Byte Stream format

in1 = new FileInputStream(inputFile1);

in2 = new FileInputStream(inputFile2);

int c1;

//Try to read 'nosuchfile.abc' till the end of File

while ((c1 = in2.read()) != -1){

System.out.println("Read from nosuchfile.abc");

}

//2. Close the try block here

//3. Add a catch block containing meaningful error messages.

//4. Add the finally block here. See instructions in the handout.

//Close the files

in1.close();

System.out.println("Closing file 'trycatch.txt' inside finally block.");

in2.close();

System.out.println("Closing file 'nosuchfile.abc' inside finally block.");

//5. Close the finally block here.

}

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

CODE:

//////////////////////////////////////////////////
//TestFinally.java

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class TestFinally {
public static void main(String[] args) {
FileInputStream in1 = null;
FileInputStream in2 = null;
//Open existing file
File inputFile1 = new File("trycatch.txt");
//Open nonexistent file
File inputFile2 = new File("nosuchfile.abc");
//1. Add try here
try {
//Get the file handlers
in1 = new FileInputStream(inputFile1);
in2 = new FileInputStream(inputFile2);
int c1;
//try to read noexistent file
while((c1 = in2.read()) != -1) {
System.out.println("Read from nosuchfile.abc");
}
//2. Close the try block
} catch(FileNotFoundException ex) {
//Catch the Runtime - FileNotFound exception (Chegg - related to query #f in the instructions)
System.out.println("Error: " + ex.getMessage());
} catch(IOException e) {
//3. Add a catch block
System.out.println("The exception is:" + e);
} finally {
//4. Add finally block
//Close the files
try {
in1.close();
} catch (Exception e) {
// Ignore exception
}
System.out.println("Closing file trycatch.txt inside finally block");
try {
in2.close();
} catch (Exception e) {
// Ignore exception
}
System.out.println("Closing file nosuchfile.abc inside finally block");
//5. Close the finally block
}


}

Add a comment
Know the answer?
Add Answer to:
3. Handling exceptions with a finally clause a. Download the following file from the class website:...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • import java.util.Scanner; import java.io.File; public class Exception2 {        public static void main(String[] args) {              ...

    import java.util.Scanner; import java.io.File; public class Exception2 {        public static void main(String[] args) {               int total = 0;               int num = 0;               File myFile = null;               Scanner inputFile = null;               myFile = new File("inFile.txt");               inputFile = new Scanner(myFile);               while (inputFile.hasNext()) {                      num = inputFile.nextInt();                      total += num;               }               System.out.println("The total value is " + total);        } } /* In the first program, the Scanner may throw an...

  • Exception handling All Exceptions that can be thrown must descend from this Java class: The getMessage(...

    Exception handling All Exceptions that can be thrown must descend from this Java class: The getMessage( ) method is inherited from this class? What are the two broad catagories of Exceptions in Java? If an Exception is not a checked exception it must extend what class? What is the difference between a checked Exception and an unchecked Exception? What are the two options a programmer has when writing code that may cause a checked Exception to be thrown? Can a...

  • SQU PORTA ATTENDANCE ENCHISE EN sed 100 bon Python's error handling process includes the finally clause...

    SQU PORTA ATTENDANCE ENCHISE EN sed 100 bon Python's error handling process includes the finally clause In the following code snippet, when is the finally clause executed inputFile = open("lyrics.txt", "-") try: line - inputFile.readline() words line.split() print (words) finally input file.close() Select one a. Only when there is an error opening the file b. Only when there is an error reading the file c The finally clause is never executed in this example d. The finally clause is always...

  • Select the correct answer. (1)     Which of the following will open a file named MyFile.txt and...

    Select the correct answer. (1)     Which of the following will open a file named MyFile.txt and allow you to read data from it?                (a)      File file = new File("MyFile.txt");           (b)      FileWriter inputFile = new FileWriter();           (c)       File file = new File("MyFile.txt");                      FileReader inputFile = new FileReader(file);           (d)      FileWriter inputFile = new FileWriter("MyFile.txt"); (2)     How many times will the following do - while loop be executed?                      int x = 11;             do {             x...

  • MUST BE IN C++ The lab is called "7.3.7.1 Exceptions: file checks" The lab is as...

    MUST BE IN C++ The lab is called "7.3.7.1 Exceptions: file checks" The lab is as follows: Objectives Familiarize the student with: situations when exceptions are thrown; handling file-related exceptions. Scenario Write a class that holds a (2×2) matrix, and add two methods to work with files: one method to load the matrix from a file (in any format) and one method to save the matrix to a file (in the same format). Add code to handle exceptional situations (file...

  • Please provide the full code...the skeleton is down below: Note: Each file must contain an int...

    Please provide the full code...the skeleton is down below: Note: Each file must contain an int at the beginning, stating the number of records in the file. Afterwards, the number of records in the file will follow. Each record that follows will consist of a last name (String), and a gpa (double). However, to test the error handling of your program, the number of records will not always match the int value. All possible combinations should be tested. 1.) Prompt...

  • Homework 1- Merge Files: 1. Design a class named MergeFiles 1 Three file names are passed...

    Homework 1- Merge Files: 1. Design a class named MergeFiles 1 Three file names are passed as command-line arguments to MergeFiles as follows: java MergeFiles filel file2 mergedFile II. MergeFiles reads names stored in files file and file2 III. Merges the two list of names into a single list IV. Sorts that single list V. Ignores repetitions VI. Writes the sorted, free-of-repetitions list to a new file named mergedFile.txt VII. The names in all three files are stored as one...

  • Exception handling is a powerful tool used to help programmers understand exception errors. This tool separates...

    Exception handling is a powerful tool used to help programmers understand exception errors. This tool separates the error handling routine from the rest of the code. In this application, you practice handling exception errors. You use sample code that was purposefully designed to generate an exception error, and then you modify the code so that it handles the errors more gracefully. For this Assignment, submit the following program: The following code causes an exception error: import java.io.BufferedReader; import java.io.IOException; import...

  • (Java) Rewrite the following exercise below to read inputs from a file and write the output...

    (Java) Rewrite the following exercise below to read inputs from a file and write the output of your program in a text file. Ask the user to enter the input filename. Use try-catch when reading the file. Ask the user to enter a text file name to write the output in it. You may use the try-with-resources syntax. An example to get an idea but you need to have your own design: try ( // Create input files Scanner input...

  • /************************************************************************************ * Program: PRG/420 Week 5 * Purpose: Week 5 Coding Assignment * Programmer: TYPE YOUR...

    /************************************************************************************ * Program: PRG/420 Week 5 * Purpose: Week 5 Coding Assignment * Programmer: TYPE YOUR NAME HERE * Class: PRG/420 * Creation Date: TYPE TODAY'S DATE HERE ************************************************************************************* * Program Summary: * This program converts a given date to a string. * The code includes exception handling for a ParseException. ************************************************************************************/ package prg420week5_codingassignment; import java.util.*; // wildcard to import all the util. classes import java.text.*; // wildcard to import all the text classes public class PRG420Week5_CodingAssignment { public static...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT