runtime_error: <stdexcept> exception<--runtime_error o this class defines the type of objects thrown as exceptions to report errors that can only be determined during runtime o class runtime_error: public exception pu ublic explicit runtime_error(const string& what_arg) 0 2018, SEU. All rights reserved. 16
© 2009, SEU. All rights reserved. © 2018, SEU. All rights reserved. 16 runtime_error:<stdexcept> exception<——runtime_error This class defines the type of objects thrown as exceptions to report errors that can only be determined during runtime. class runtime_error : public exception { public: explicit runtime_error (const string& what_arg); };
创建一个临时异常对象 double quotient(int numerator, int dendacurT if (denominator==O) throw Divide ByzeroException O return static cast<double>Inumeratorldenominator: Enter two integers (end-of-file to end): 1007 The quotient is: 14 2857 int main (t int number1,number2. Enter two integers(end-of-file to end):1000 Exception occurred: attempted to divide by zero double result. while(cin>>number1> Enter two integers (end-of-file to end): AZ try result= quotient(number1, number2); catch(DivideByzeroException divide ByZeroException) cout<<Exception occurred: < divideByzeroException. what(<<endl; 打印异常错误信息 17
© 2009, SEU. All rights reserved. © 2018, SEU. All rights reserved. 17 double quotient (int numerator, int denominator ){ if (denominator == 0) throw DivideByZeroException(); return static_cast<double>(numerator)/denominator; } int main(){ int number1,number2; double result; while (cin>>number1>>number2){ try{ result = quotient(number1,number2); } catch (DivideByZeroException & divideByZeroException){ cout<<“Exception occurred:” << divideByZeroException.what()<<endl; } } 打印异常错误信息 创建一个临时异常对象
16.2 Exception-Handling overview -try、 throw子句 o throw表达式抛出异常为异常处理的第一步。 try语句中包含可能引起异常的语句和在异常发生 时应该跳过的语句(如 numerator/ denominator) 异常可能在try语句块的代码中,也可能出现在try 语句中其它函数的调用和深层嵌套的函数调用中 0 2018, SEU. All rights reserved. 18
© 2009, SEU. All rights reserved. © 2018, SEU. All rights reserved. 18 16.2 Exception-Handling Overview -- try、throw子句 throw表达式抛出异常为异常处理的第一步。 try语句中包含可能引起异常的语句和在异常发生 时应该跳过的语句(如numerator /denominator) 异常可能在try语句块的代码中,也可能出现在try 语句中其它函数的调用和深层嵌套的函数调用中