c++中的try catch的示例
时间: 2023-10-28 08:10:33 浏览: 88
C 语言中的 try catch 的示例代码如下:
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
int dividend = 20;
int divisor = 0;
int quotient;
quotient = dividend / divisor;
printf("Quotient : %d\n", quotient);
return 0;
}
```
可以使用 try catch 块来捕获除数为 0 时的异常:
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
int dividend = 20;
int divisor = 0;
int quotient;
try {
if (divisor == 0) {
throw "Division by zero error";
} else {
quotient = dividend / divisor;
printf("Quotient : %d\n", quotient);
}
} catch (const char* message) {
printf("%s\n", message);
}
return 0;
}
```
在运行时,该代码将输出:"Division by zero error"。
阅读全文