講一個經典案例除以0,首先創造一個DivideByZeroEXception類別繼承runtime_error。在C++中double除以0並不會報錯,所以主動用throw丟出DivideByZeroEXception,並在catch段落呼叫what()方法顯示錯誤原因,最外面用while()產生一個無限迴圈
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
詳細範例見Fig. 16.1: DivideByZeroException.h與Fig. 16.2: Fig16_02.cpp