Question

Program 2 #include #include using namespace std; int main() { int total = 0; int num...

Program 2

#include 
#include 

using namespace std;

int main() {
    int total = 0;
    int num = 0;
    
    ifstream inputFile;
    
    inputFile.open("inFile.txt");

    while(!inputFile.eof()) {   // until we have reached the end of the file
            inputFile >> num;
            total += num;
    }
    
    inputFile.close();
    
    cout << "The total value is " << total << "." << endl;

Lab Questions:

  1. We should start by activating IO-exceptions. Do so using the same method in Step 3 of the Program 1 assignment above, except that instead of cin, our input stream is inputFile, which is an instance of an ifstream instead of an iostream.
  2. We will now test the program knowing the input file does not exist. Run the program (making sure there isn't a file named "inFile.txt" in the same folder as your program). You should get an error message describing your runtime exception and perhaps even showing a file name containing more detailed information. If you can, try to find this file and open it with a simple text editor like Notepad. The information in this file may not mean much to you right now, but someday it might help you track down exactly what's wrong with your program when the error isn't so simple. Conversely, if experienced hackers can track this information down, they might use the information to take advantage of weak points in the security of your program. This is why it is best to find and handle any exceptions that can be thrown by your program before publishing it.
  3. We don't want to expose any sensitive information if the input file does not exist. Add a try/catch block such that if the input file is not found, the problem is reported and a total of 0 is displayed. Run the program to see if you did it correctly: only your error message should be visible, not any sensitive information about your program or file system.
  4. Create a file named inFile.txt using a plain text editor. Enter only integer values separated by spaces or new-lines into the file, and save the file in the same folder as the program (if you are using a IDE, then put it in the main project folder). Run the program to verify that the program functions correctly with a valid input file.
  5. Now change a number to an invalid value, such as 'four', and run the program again. Did the program display your "file not found" error message? The problem is that C++ uses the same exception for all of its IO problems. Depending on your compiler, the exception's what() method may provide useful information to distinguish what cause the error. Unfortunately, it may also or instead provide sensitive information that you don't want users to be able to see. Fortunately, we can nest try/catch blocks to isolate which problem caused the exception. Let's add another try/catch block inside the loop. In addition to narrowing where the exception might have occurred, this will allow our program to report the invalid data, resume processing, and produce correct results for all the valid data given afterwards. Use the following code for your catch block.
    catch(ifstream::failure& iof) {
        cout << "Skipping non-integer value, found after "<> ignore;
    }
    

    Note that since we are analyzing each number independently, we simply read in the next token to a dummy variable, rather than use the ignore() method. Run your program with a variety of invalid and valid values in your file to test how well the program works.

  6. If you selected good test values, you may have noticed that your program currently includes the integer components of invalid values like '10forward' or '4ever'. We already know how to fix this! Add the following code after reading in some value to num:
    // if this number was part of a non-integer word, throw an exception
    if( !( inputFile.eof() || isspace(inputFile.peek()) ) ) {
         throw #
    }
    

    The change in the condition from Program 1 accounts for the fact that, since we are analyzing each number at a time, it may be followed by any whitespace, rather than just '\n'. And since we are working with files, we should also check if we are at the end of the file. Now, add an appropriate catch block to handle the exception we have just added. Hint: draw from Program 1 Step 6 and Program 2 Step 5.

  7. Run your program with all sorts of values and verify that it handles all exceptions as smoothly as it should.
  8. Complete the security checklist for Program 2.
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Summary:

During the execution of a program, things can, and do go wrong. The user may enter inappropriate data, a device may go offline, necessary disk space for output may not be available, etc. Errors occurring at runtime are known as exceptions and exception handling is the process designed to handle exceptions. Failure to properly handle an exception can cause a program to abort and/or expose sensitive information about the program and the environment in which the program is executing.

Description:

When an exception occurs, C++ creates an exception object containing information about the error and the program state at the time of the error. There are numerous (about 20) exception classes defined in the C++ libraries.

Once the exception object has been constructed, it is handed to the C++runtime system. This is called ‘throwing’ an exception. The C++runtime system must then locate an exception handler. In searching for an exception handler, the runtime system begins with the method in which the exception occurred. If this method is not prepared to handle the exception, the runtime system will search the call stack in reverse in search of a suitable exception handler. For example, if methodA calls methodB which calls methodC and an exception occurs during the execution of methodC, the runtime system will search methodC first, then methodB, and lastly methodA for an exception handler. When an appropriate exception handler is found, the runtime system turns over the exception object to the handler. The selected exception handler is said to ‘catch’ the exception.

In addition to special exception objects, C++ allows any object or primitive data type to be thrown. While these data might not contain useful information about the error or program state like an exception object, they can be caught in exactly the same way. This allows programmers to code simple custom exception-like flow control within their own programs, without having to create their own class inheriting an existing exception class.

Risk – How Can It Happen?

In some languages (but not C++), certain exceptions are known as checked exceptions and exception handling, or catching checked exceptions, is required to be included in the program. Other exceptions (and all exceptions in C++) are known as unchecked exceptions, which do not require an exception handler. Most unchecked exceptions, however, cause the program to display an error message (which may be a security issue since it exposes the inner details of your application) and stop execution when not handled. Others, such as problems with input/output, must be activated by the programmer before the runtime will throw them. Exception handling provides a way for the program to possibly recover from an error or at least terminate in a graceful manner.

code responsibly – how to handle exceptions?

  1. Know your exceptions: Every method in the standard C++ library has documentation describing when any exceptions might be thrown. Although unchecked exceptions do not require exception handling code, consider handling them or providing code checks such that the exception can never occur.
  2. Order exception handlers correctly: When more than one exception handler is desired, code them in the order that they are more likely to occur. When a generic exception handler is also used, it should appear last.
  3. Handle exceptions appropriately: Once an exception occurs, the remaining statements of the try block will not be executed. Therefore, it is important that the exception handler recover from the exception such that the program can continue. If recovery in not possible, exit the program.
  4. An exception should not expose sensitive information: Some exception objects define messages that expose information about the state of the program and/or the file system. Therefore, be careful when allowing default exception behavior or when using an exception’s what() method.
  5. runtime_error exceptions are usually thrown due to bugs in the program. These bugs should be corrected during development.
Add a comment
Know the answer?
Add Answer to:
Program 2 #include #include using namespace std; int main() { int total = 0; int num...
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...

  • For practice using exceptions, this exercise will use a try/catch block to validate integer input from...

    For practice using exceptions, this exercise will use a try/catch block to validate integer input from a user. Write a brief program to test the user input. Use a try/catch block, request user entry of an integer, use Scanner to read the input, throw an InputMismatchException if the input is not valid, and display "This is an invalid entry, please enter an integer" when an exception is thrown. InputMismatchException is one of the existing Java exceptions thrown by the Scanner...

  • C++ with comments please! // numberverifier.cpp #include <iostream> #include <exception> using std::cout; using std::cin; using std::endl;...

    C++ with comments please! // numberverifier.cpp #include <iostream> #include <exception> using std::cout; using std::cin; using std::endl; #include <cmath> #include <cstring> class nonNumber : public exception { public: /* write definition for the constructor */ -- Message is “An invalid input was entered” }; int castInput( char *s ) { char *temp = s; int result = 0, negative = 1; // check for minus sign if ( temp[ 0 ] == '-' ) negative = -1; for ( int i...

  • Write a program that prompts the user to enter a person's birth date in numeric form...

    Write a program that prompts the user to enter a person's birth date in numeric form (e.g. 8-27-1980) and outputs the date of birth in the format of month day, year (e.g. August 27, 1980). Your program must work for three types of exceptions - invalid day, invalid month and invalid year (year must be between 1915 and 2015). Make these as class driven exceptions. Use one try-catch block with separate catches for the exception classes to handle errors for...

  • C++ Your assignment this week is to make your fractionType class safe by using exception handling....

    C++ Your assignment this week is to make your fractionType class safe by using exception handling. Use exceptions so that your program handles the exceptions division by zero and invalid input. · An example of invalid input would be entering a fraction such as 7 / 0 or 6 / a · An example of division by zero would be: 1 / 2 / 0 / 3 Use a custom Exception class called fractionException. The class must inherit from exception...

  • #include <fstream> #include <iostream> #include <cstdlib> using namespace std; // Place charcnt prototype (declaration) here int...

    #include <fstream> #include <iostream> #include <cstdlib> using namespace std; // Place charcnt prototype (declaration) here int charcnt(string filename, char ch); int main() { string filename; char ch; int chant = 0; cout << "Enter the name of the input file: "; cin >> filename; cout << endl; cout << "Enter a character: "; cin.ignore(); // ignores newline left in stream after previous input statement cin.get(ch); cout << endl; chcnt = charcnt(filename, ch); cout << "# of " «< ch« "'S:...

  • Wrote a program called ExceptionalDivide that asks the user for 2 integer values and displays the...

    Wrote a program called ExceptionalDivide that asks the user for 2 integer values and displays the quotient of the first value divided by the second value. Make sure the your program reads in the two input values as ints. Your program must catch either of two exceptions that might arise and crash your program java.util.InputMismatchException //wrong data type inputted java.lang.ArithmeticException //divide by zero error Once you catch these exceptions, your program must print out a message explaining what happened and...

  • #include <iostream> using namespace std; int main() {    } Write a program that, given a...

    #include <iostream> using namespace std; int main() {    } Write a program that, given a user-specified integer, prints out the next 10 integers (in increasing order; each on its own line). For example, given an input of 3, the console content following a run of the completed program will look as follows: Enter a number: 3 4 5 6 7 8 9 10 11 12 13

  • Placing Exception Handlers File ParseInts.java contains a program that does the following: Prompts for and reads...

    Placing Exception Handlers File ParseInts.java contains a program that does the following: Prompts for and reads in a line of input Uses a second Scanner to take the input line one token at a time and parses an integer from each token as it is extracted. Sums the integers. Prints the sum. Save ParseInts to your directory and compile and run it. If you give it the input 10 20 30 40 it should print The sum of the integers...

  • 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) {...

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