LearnFrenzy
Sign in Take a free test

Exception Handling · Exception Handling Programs · Question 7

Matrix class that throws on dimension mismatch in C++ Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

Write a Matrix class whose constructor throws std::invalid_argument for zero sizes and whose operator* and at() throw for incompatible dimensions or bad indices; demonstrate each error being caught.

Solution
main.cpp
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>

class Matrix {
    std::size_t r_, c_;
    std::vector<int> a_;
public:
    Matrix(std::size_t r, std::size_t c) : r_(r), c_(c), a_(r * c, 1) {
        if (r == 0 || c == 0) throw std::invalid_argument("matrix dimensions must be positive");
    }
    int& at(std::size_t i, std::size_t j) {
        if (i >= r_ || j >= c_) throw std::out_of_range("index (" + std::to_string(i) + "," + std::to_string(j) + ") outside " + std::to_string(r_) + "x" + std::to_string(c_));
        return a_[i * c_ + j];
    }
    Matrix operator*(const Matrix& o) const {
        if (c_ != o.r_) throw std::invalid_argument("cannot multiply " + std::to_string(r_) + "x" + std::to_string(c_) + " by " + std::to_string(o.r_) + "x" + std::to_string(o.c_));
        Matrix m(r_, o.c_);
        for (std::size_t i = 0; i < r_; ++i)
            for (std::size_t j = 0; j < o.c_; ++j) {
                int s = 0;
                for (std::size_t k = 0; k < c_; ++k) s += a_[i * c_ + k] * o.a_[k * o.c_ + j];
                m.a_[i * o.c_ + j] = s;
            }
        return m;
    }
};

int main() {
    Matrix a(2, 3), b(3, 2);
    Matrix p = a * b;
    std::cout << "p(0,0) = " << p.at(0, 0) << '\n';
    try { Matrix bad(0, 4); } catch (const std::invalid_argument& e) { std::cout << e.what() << '\n'; }
    try { a * a; } catch (const std::invalid_argument& e) { std::cout << e.what() << '\n'; }
    try { p.at(2, 0) = 9; } catch (const std::out_of_range& e) { std::cout << e.what() << '\n'; }
    return 0;
}

Output Verified by compiling and running

p(0,0) = 3
matrix dimensions must be positive
cannot multiply 2x3 by 2x3
index (2,0) outside 2x2

A constructor cannot return an error code, so throwing is the way to refuse to create an invalid matrix. Messages include the actual sizes, which makes bugs easy to find.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links