C++_try_catch
1. try_catch
try {
语句组
}
catch(异常类型) {
异常处理代码
}
2. 举例
2.1 try_catch_throw例子
#include <iostream>
#include <string>
using namespace std;
int main()
{
int a;
try{
cin >> a;
if(a > 10)
{
cout << "输入合格 a = " << a << endl;
}else
{
throw a;
}
}catch(int res)
{
cout << "异常!!!输入值小于10 res = " << res << endl;
}
return 0;
}
输出结果:
[root@tianyiyi try_catch]# ./try_catch
12
输入合格 a = 12
[root@tianyiyi try_catch]# ./try_catch
3
异常!!!输入值小于10 res = 3
2.2 多个catch
#include <iostream>
#include <string>
using namespace std;
class Base{ };
class Derived: public Base{ };
int main(){
try{
throw Derived(); //抛出自己的异常类型,实际上是创建一个Derived类型的匿名对象
cout<<"This statement will not be executed."<<endl;
}catch(int){
cout<<"Exception type: int"<<endl;
}catch(char *){
cout<<"Exception type: cahr *"<<endl;
}catch(Derived){
cout<<"Exception type: Derived"<<endl;
}
return 0;
}
输出结果
[root@tianyiyi try_catch]# ./try_catch
Exception type: Derived
2.3 嵌套的try_catch
#include <iostream>
#include <string>
using namespace std;
void fun()
{
int a = 1;
try
{
cout << "fun try block" << endl;
throw -1;
}
catch(int ans)
{
cout << "fun throw ans = " << ans << endl;
}
}
int main()
{
int a;
try{
fun();
cout << "main try block" << endl;
}catch(int ans)
{
cout << "main throw ans = " << ans << endl;
}
return 0;
}
输出结果
从输出结果知晓,异常不会跨级抛出
[root@tianyiyi try_catch]# ./try_catch
fun try block
fun throw ans = -1
main try block
3. 和if_else的区别
- if_else是流程控制语句,try_catch是异常处理语句。
4. throw在C++函数中的应用
static int fun1(int arg1,int arg2) throw(); // 表示该函数不会抛出异常
static int fun1(int arg1,int arg2) throw(...); // 表示该函数可能会抛出各种类型的异常
static int fun1(int arg1,int arg2) throw(int); // 表示该函数会抛出int类型的异常