如何抛出一个 C++ 异常?
异常处理用于处理异常。我们可以使用 try catch 块来保护代码。异常可以在代码块中的任何地方抛出。关键字“throw”用于抛出异常。
以下是 C++ 语言中抛出的一个示例:
示例
#include <iostream> using namespace std; int display(int x, int y) { if( y == 0 ) { throw "Division by zero condition!"; } return (x/y); } int main () { int a = 50; int b = 0; int c = 0; try { c = display(a, b); cout << c << endl; } catch (const char* msg) { cerr << msg << endl; } return 0; }
输出
以下是输出
Division by zero condition!
广告