- Microsoft Visual C++ Windows Applications by Example
- Stefan Bjornander
- 256字
- 2021-07-02 12:02:23
Exceptions
So far, we have handled errors in a rather crude way by using the assert macro. Another, more sophisticated, way is to use exceptions. The idea is that when an error occurs, the method throws an exception instead of returning a value. The calling method can choose to handle the exception or to ignore it, in which case it is in turn thrown to its calling method and so on. If no method catches the exception, the execution of the program will finally abort with an error message.
The idea behind exceptions is that the method who discovers the error just throws an exception. It is the calling method that decides what to do with it. The main advantage with exceptions is that we do not have to check for errors after every function call; an exception is thrown at one point in the code and caught at another point. There is a predefined class exception that can be thrown. It is also possible to throw exception of other classes, which may be a subclass of exception, but it does not have to.
Exception.cpp
#include <iostream> #include <exception> using namespace std; double divide(double dNumerator, double dDenominator) { if (dDenominator == 0) { throw exception("Division by zero."); } return dNumerator / dDenominator; } double invers(double dValue) { return divide(1, dValue); } void main() { double dValue; cout << ": "; cin >> dValue; try { cout << "1 / " << dValue << " = " << invers(dValue) << endl; } catch (exception exp) { cout << exp.what() << endl; } }
- 3ds Max 2016中文版完全自學手冊
- 中文版After Effects CC 2020完全自學一本通
- 中文版Premiere影視編輯課堂實錄
- Oracle VM Manager 2.1.2
- 畫筆圣經 Photoshop專業繪畫技法
- 中文版Maya 2022完全自學教程
- Quickstart Apache Axis2
- Photoshop CC從入門到精通(全彩超值版)
- Ogre 3D 1.7 Beginner's Guide
- Photoshop+CorelDRAW平面設計實例教程(第4版)
- After Effects影視特效立體化教程:After Effects 2021(微課版)
- Microsoft Silverlight 5: Building Rich Enterprise Dashboards
- 3D打印輕松實踐:從材料應用到三維建模
- Microsoft Silverlight 4 and SharePoint 2010 Integration
- OpenAM