Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In the following function: void WriteToFile(parameters) { . . . try { while (con

ID: 3530555 • Letter: I

Question

In the following function: void WriteToFile(parameters) { . . . try { while (condition) { DoSomething(arguments) . . . } } catch (BadData) { . . . throw; } . . . } PLEASE, ANSWERS THE FOLLOWING QUESTIONS: a. What would happen if we delete the throw statement in the exception handler? b. What would happen if we changed throw to return? c. Consider the division-by-zero program at the end of the WriteToFile function. How would you change the main function so that the program terminates if a denominator is found to be 0?

Explanation / Answer

When you want to output text to a file it's better to use a Writer class instead of an OutputStream such as the BufferedOutputStream since the purpose of Writer classes are to handle textual content.
With the BufferedWriter (as opposed to the BufferedOutputStream) you don't have to translate your String parameter to a byte array, and there is also a handy method for writing a new line character.
In this example we simply write two lines of text, and finally we call flush on the BufferedWriter object before closing it.

importjava.io.BufferedWriter;
importjava.io.FileNotFoundException;
importjava.io.FileWriter;
importjava.io.IOException;

/**
*
* @author javadb.com
*/

publicclassMain {

/**
* Prints some data to a file using a BufferedWriter
*/

publicvoidwriteToFile(String filename) {

BufferedWriter bufferedWriter =null;

try{

//Construct the BufferedWriter object
bufferedWriter =newBufferedWriter(newFileWriter(filename));

//Start writing to the output stream
bufferedWriter.write("Writing line one to file");
bufferedWriter.newLine();
bufferedWriter.write("Writing line two to file");

}catch(FileNotFoundException ex) {
ex.printStackTrace();
}catch(IOException ex) {
ex.printStackTrace();
}finally{
//Close the BufferedWriter
try{
if(bufferedWriter !=null) {
bufferedWriter.flush();
bufferedWriter.close();
}
}catch(IOException ex) {
ex.printStackTrace();
}
}
}

/**
* @param args the command line arguments
*/

publicstaticvoidmain(String[] args) {
newMain().writeToFile("myFile.txt");
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote