User Tools

Site Tools


c_-_c_exception_handling:throwing_exceptions

C - C++ Exception Handling - Throwing Exceptions

#include <iostream>
#include <stdexcept>
using std::cin;
using std::cout;
using std::endl;
using std::runtime_error;
 
class DivideByZeroException : public runtime_error
{
public:
   DivideByZeroException::DivideByZeroException(): runtime_error( "attempted to divide by zero" ) {}
};
 
 
double quotient( int numerator, int denominator )
{
  throw DivideByZeroException(); // terminate function
 
  return 0;
}
 
 
int main()
{
  try
  {
    double result = quotient( 1, 1 );
    cout << "The quotient is: " << result << endl;
  }
  catch ( DivideByZeroException &divideByZeroException )
  {
    cout << "Exception occurred: " << divideByZeroException.what() << endl;
  }
 
  return 0;
}
c_-_c_exception_handling/throwing_exceptions.txt · Last modified: 2020/07/15 10:30 by 127.0.0.1

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki