如何丟擲一個 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!
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP