try与catch,throw

try

try块

try块用于包含可能抛出异常的代码。它的语法如下:

try {
    // 可能抛出异常的代码
}

catch块

catch块用于捕获和处理异常。它紧跟在try块之后,语法如下:

catch (ExceptionType e) {

// 处理异常的代码

}

其中,ExceptionType是异常的类型,e是捕获的异常对象。

throw语句

throw语句用于在检测到错误时抛出异常。语法如下:

throw exception;

其中,exception是要抛出的异常对象。

示例
#include<bits/stdc++.h>
using namespace std;
double division(int a, int b) {
   if (b == 0) {
       throw "Division by zero condition!";
   }
   return (a / b);
}
int main() {
   int x = 50;
   int y = 0;
   double z = 0;
   try {
       z = division(x, y);
       cout << z << endl;
   } catch (const char* msg) {
       cerr << msg << endl;
   }

	return 0;
}