64,643
社区成员
发帖
与我相关
我的任务
分享
// Fig. 16.1: DivideByZeroException.h
// Class DivideByZeroException definition.
#include <stdexcept> // stdexcept header file contains runtime_error
using std::runtime_error; // standard C++ library class runtime_error
// DivideByZeroException objects should be thrown by functions
// upon detecting division-by-zero exceptions
class DivideByZeroException : public runtime_error
{
public:
// constructor specifies default error message
DivideByZeroException::DivideByZeroException()
: runtime_error( "attempted to divide by zero" ) {}
}; // end class DivideByZeroException
//----------------
// Fig. 16.2: Fig16_02.cpp
// A simple exception-handling example that checks for
// divide-by-zero exceptions.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
#include "DivideByZeroException.h" // DivideByZeroException class
// perform division and throw DivideByZeroException object if
// divide-by-zero exception occurs
double quotient( int numerator, int denominator )
{
// throw DivideByZeroException if trying to divide by zero
if ( denominator == 0 )
throw DivideByZeroException(); // terminate function
// return division result
return static_cast< double >( numerator ) / denominator;
} // end function quotient
int main()
{
int number1; // user-specified numerator
int number2; // user-specified denominator
double result; // result of division
cout << "Enter two integers (end-of-file to end): ";
// enable user to enter two integers to divide
while ( cin >> number1 >> number2 )
{
// try block contains code that might throw exception
// and code that should not execute if an exception occurs
try
{
result = quotient( number1, number2 );
cout << "The quotient is: " << result << endl;
} // end try
// exception handler handles a divide-by-zero exception
catch ( DivideByZeroException ÷ByZeroException )
{
cout << "Exception occurred: "
<< divideByZeroException.what() << endl;
} // end catch
cout << "\nEnter two integers (end-of-file to end): ";
} // end while
cout << endl;
return 0; // terminate normally
} // end main