本文概述
- 没有try / catch的C ++示例
- C ++尝试/捕获示例
没有try / catch的C ++示例
#include <
iostream>
using namespace std;
float division(int x, int y) {
return (x/y);
}
int main () {
int i = 50;
int j = 0;
float k = 0;
k = division(i, j);
cout <
<
k <
<
endl;
return 0;
}
【C++异常处理: try-catch】输出:
Floating point exception (core dumped)
C ++尝试/捕获示例
#include <
iostream>
using namespace std;
float division(int x, int y) {
if( y == 0 ) {
throw "Attempted to divide by zero!";
}
return (x/y);
}
int main () {
int i = 25;
int j = 0;
float k = 0;
try {
k = division(i, j);
cout <
<
k <
<
endl;
}catch (const char* e) {
cerr <
<
e <
<
endl;
}
return 0;
}
输出:
Attempted to divide by zero!
推荐阅读
- C++用户自定义的异常
- C++模板template用法
- C++字符串用法
- C++栈stack用法
- C++信号处理
- C++ STL集合set
- C++队列queue用法
- C++常见程序实例
- C++ int转换为字符串