Question

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 not found and no rights to file), print a message and re-throw an exception. Add a try-catch block in the proper places. Simulate both situations handled (try to load a nonexistent file, and try to save a file in a path where you have no proper rights).

Simulate both situations handled

File not found at: path
No rights to write to file: path

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

#include<iostream>
#include<fstream>
using namespace std;
class matrix //defining a class matrix
{
public:
int a[2][2]; //a 2*2 array
matrix()      //default constructor to initialise each element with 0
{
    a[0][0]=0;
    a[0][1]=0;
    a[1][0]=0;
    a[1][1]=0;
}
void loads(string fName) //function to load data from from file
{
    fstream f;    //an fstream variable
    try     //try block
    {
      f.open(fName, ios::in);//tries opening the file
      if(!f)    //if file not able to open means file not found
        throw 10;   //throws an exception
    }
    catch(int x)    //catches the exception
    {
      cout<<"File not found at: "<<fName;//prints the file not found error
      throw 10;   //re-throw the exception to be caught in main function
    }
    f>>a[0][0]; //if file found then loading data from file
    f>>a[0][1];
    f>>a[1][0];
    f>>a[1][1];
    f.close();    //closing the file
}
void saves(string fName)//saves array in file
{
    fstream f; //an fstream variable
    try
    {
      f.open(fName, ios::out); //opening file in output mode
      if(!f)    //if no right to write the file
        throw 20;   //throw exception
    }
    catch(int x) //catches exception
    {
      cout<<"No rights to write to file: "<<fName; //prints the error
      throw 20;   //re-throws the exception
    }
    f<<a[0][0];//if file has write access the writes to file
    f<<a[0][1];
    f<<a[1][0];
    f<<a[1][1];
    f.close();//closes the file
}
};
int main()
{
matrix m ;//defining a class variable

try
{
    m.loads("example1.txt");//calls loads function
}
catch(int x)//if loads function throws an exception, it is caught by this block
{
    cout<<endl;
}
try
{
    m.saves("example.txt");//calling saves function
}
catch(int x)//if saves function throws an exception, it is caught by this block
{
    cout<<endl;
}
}

INPUT: In file "example.txt"

"example.txt" is made Read-only, so to throw no rights to write in the file.

There is no file named "example1.txt", so to throw exception of file not found.

OUTPUT:

Ask any questions If you have in comment section below.

Please rate the answer.

Add a comment
Know the answer?
Add Answer to:
MUST BE IN C++ The lab is called "7.3.7.1 Exceptions: file checks" The lab is as...
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
  • MUST BE IN C++ The lab is called "7.5.9.1 Exceptions: including information in exceptions" The lab...

    MUST BE IN C++ The lab is called "7.5.9.1 Exceptions: including information in exceptions" The lab is as follows: Objectives Familiarize the student with: using exceptions in real programs; the simplification of exception throwing; throwing exceptions in constructors. Scenario IP header – imagine you have a class or struct (choose one) describing an IP header which holds (apart from other fields) two string fields that contain Source IP Address and Destination IP Address. Check these two fields and throw an...

  • Can anyone help me with this lab? Thanks The BankAccount.h: The BankAccount.cpp: Exceptions Lab In this...

    Can anyone help me with this lab? Thanks The BankAccount.h: The BankAccount.cpp: Exceptions Lab In this lab you will get practice with exceptions by adding them to a class that represents bank accounts. I have provided two files, BankAccount.h and BankAccount.cpp, which have the code for the class itself. Your task is to modify the code to have it throw exceptions under the conditions listed below, then write a main which uses try/catch blocks to display error messages when the...

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

  • Part 2: Programming with Exceptions In this part of the lab , you will write a...

    Part 2: Programming with Exceptions In this part of the lab , you will write a program that fetches the information stored at a give URL on the web and saves that data to a file. This will also include networking and file operations and partly an exercise in using exceptions. For doing I/O, Java has a pair of nice abstractions: InputStream and OutputStream. These are abstract classes in the package java.io. An InputStream is a place from which you...

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

  • Lab 3 Step One First, create an empty directory for lab3. There is no starter code for this lab. You will be throwing an...

    Lab 3 Step One First, create an empty directory for lab3. There is no starter code for this lab. You will be throwing and catching exceptions in this exercise. Create a file called RuntimeException.h and put the following code in it. #include <string> class RuntimeException { private: string errorMsg; public: RuntimeException(const string& err) { errorMsg = err; } string getMessage() const { return errorMsg; } } Step Two In a new .cpp file in your directory, write a main function...

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

  • Lab 3 Step One First, create an empty directory for lab3. There is no starter code...

    Lab 3 Step One First, create an empty directory for lab3. There is no starter code for this lab. You will be throwing and catching exceptions in this exercise. Create a file called RuntimeException.h and put the following code in it. #include <string> class RuntimeException { private: string errorMsg; public: RuntimeException(const string& err) { errorMsg = err; } string getMessage() const { return errorMsg; } } Step Two In a new .cpp file in your directory, write a main function...

  • NO VECTORS PLEASE Start a simple Matrix template class In this lab, you’ll be writing a...

    NO VECTORS PLEASE Start a simple Matrix template class In this lab, you’ll be writing a template class to represent a matrix. Because it’s a template, your matrix class will be able to work with different types of underlying data. Start by creating a new file matrix.hpp. Inside this file, start to write your matrix template class. Here’s a start for the class definition: template <class T> class Matrix { private: int _rows; int _cols; T** data; public: Matrix(int rows,...

  • Lab Description : Exercise : a) Create an interface named ReadAndWriteFile, that has readAndReturnFile() and writeFile()...

    Lab Description : Exercise : a) Create an interface named ReadAndWriteFile, that has readAndReturnFile() and writeFile() methods. b) readAndReturnFile() and writeFile() both throws IOException, FileNotFoundException and Exception. c) Create a class named DealingWithTextFile that implements ReadAndWriteFile. This class read and write txt files. d) Create a class named DealingWithCsvFile that implements ReadAndWriteFile. This class read and write csv files. - Please mention that you have to deal with exceptions, use a dialog message to catch the exceptions. e) DealingWithTextFile class...

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