Presentation is loading. Please wait.

Presentation is loading. Please wait.

C++面向对象程序设计 谭浩强编著 授课教师:姬广永 学习网站:http://www.xin126.cn.

Similar presentations


Presentation on theme: "C++面向对象程序设计 谭浩强编著 授课教师:姬广永 学习网站:http://www.xin126.cn."— Presentation transcript:

1 C++面向对象程序设计 谭浩强编著 授课教师:姬广永 学习网站:

2 第8章 c++工具 异常处理 命名空间

3 异常处理 int Div(int x,int y) { return x/y; } int main(){
cout<<"5/2="<<Div(5,2)<<endl; cout<<"8/0="<<Div(8,0)<<endl; cout<<"7/1="<<Div(7,1)<<endl; cout<<"that is ok.\n";}

4 C++异常处理机制 C++异常处理机制是一个用来有效地处理运行错误的非常强大且灵活的工具,它提供了更多的弹性、安全性和稳固性,克服了传统方法所带来的问题. 异常的抛出和处理主要使用了以下三个关键字: try、 throw 、 catch 。

5 异常处理 int Div(int x,int y) { if(y==0) throw y; //抛出异常 int main(){
return x/y; } int main(){ try{ cout<<"5/2="<<Div(5,2)<<endl; cout<<"8/0="<<Div(8,0)<<endl; cout<<"7/1="<<Div(7,1)<<endl; } catch( int ){ cout<<"except of deviding zero.\n"; } cout<<"that is ok.\n"; }

6 异常处理 try { 包含可能抛出异常的语句; } catch(类型名 [形参名]) // 捕获特定类型的异常 { } catch(类型名 [形参名]) // 捕获特定类型的异常 { } catch(...) // 三个点则表示捕获所有类型的异常 { }

7 P264 例8.1

8 8.2命名空间 标准C++引入命名空间主要是为了避免成员的名称冲突。 所谓命名空间,实际上就是一个由程序设计者命名的内存区域。
namespace ns1 //指定命名空间ns1 {int a; double b; } namespace ns2 //指定命名空间ns2

9 #include<iostream>
namespace ns1 //指定命名空间ns1 {int a; double b; } namespace ns2 //指定命名空间ns2 int main() { std::cin>>ns1::a; std::cout<<ns1::a; std::cin>>ns2::b; std::cout<<ns2::b; }

10 p285 习题3.


Download ppt "C++面向对象程序设计 谭浩强编著 授课教师:姬广永 学习网站:http://www.xin126.cn."

Similar presentations


Ads by Google