SVN / public / code / vorlesung-12 / ExceptionDemoMain.cpp

Revision 8201
Date
Committerhb1003
Download
// Copyright 2026, University of Freiburg,
// Chair of Algorithms and Data Structures.
// Author: Hannah Bast <bast@cs.uni-freiburg.de>

#include <iostream>

// Our own exception class.
class PassiveAggressiveException : public std::exception {
public:
  PassiveAggressiveException() {}
  const char *what() const noexcept {
    return "Are you sure you want to divide by zero?";
  }
};

// Integer division.
int divide(int x, int y) {
  if (y == 0) {
    throw PassiveAggressiveException();
    // throw std::runtime_error("Division by zero");
  }
  return x / y;
}

// Compute modulo zu Fuß.
int modulo(int number, int modulus) {
  return number - modulus * divide(number, modulus);
}

// Main function.
int main(int argc, char **argv) {
  // Parse command-line arguments.
  if (argc != 3) {
    std::cerr << "Usage: " << argv[0] << " <number> <modulus>" << std::endl;
    return 1;
  }
  int number = std::stoi(argv[1]);
  int modulus = std::stoi(argv[2]);

  // Compute modulo.
  int result;
  try {
    result = modulo(number, modulus);
  } catch (const PassiveAggressiveException &e) {
    std::cerr << "Caught it: " << e.what() << std::endl;
    return 1;
  }
  std::cout << number << " mod " << modulus << " = " << result << std::endl;
  return 0;
}