笔记:C++学习之旅---try语句和异常处理
生活随笔
收集整理的這篇文章主要介紹了
笔记:C++学习之旅---try语句和异常处理
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
異常處理機制為程序中異常檢測和異常處理這兩部分的協作提供支持,在C++語言中,異常處理包括:
*throw表達式(throw expression),異常檢測部分使用throw表帶是來表示它遇到的了無法處理的問題,我們說throw引發了異常。
*try語句塊(try block),異常處理部分使用try語句處理異常。try語句塊以關鍵字try開始,并以一個或多個catch自居結束。try語句快中代碼拋出的異常通常會被某個catch自居處理。因為catch自居”處理“異常,所以它們也被稱作異常處理代碼。
*一套異常類(exception class),用于在throw表達式和相關的catch自居之間傳遞異常具體信息。
例子:
編寫一段程序,從標準輸入讀取兩個整數,輸出第一個數除以第二個數的結果,使用try語句塊去捕獲異常。當第二個數是0時跑出異常,catch子句應該為用戶輸出一條提示信息,詢問其是否輸入新數并重新執行try語句塊的內容。
#include
<iostream>
<iostream>
using
namespace
std;
namespace
std;
int
main()
main()
{
int
a,b;
cout<<
"please input two integers\n"
;
"please input two integers\n"
;
while
(cin>>a>>b)
{
try
{
if
(b == 0)
throw
runtime_error
(
"分母不能為0"
);
//拋出異常
cout<<
static_cast
<
double
>(a) / b<<endl;
static_cast
<
double
>(a) / b<<endl;
cout<<
"please input two integers"
<<endl;
"please input two integers"
<<endl;
}
catch
(
runtime_error
err) {
//捕獲異常
cout<<err.what()<<endl;
cout<<
"Try again\nplease input two integers"
<<endl;
"Try again\nplease input two integers"
<<endl;
}
}
return
0;
}
Static 局部靜態變量
#include
<iostream>
<iostream>
using
namespace
std;
namespace
std;
size_t
add(
int
n
)
add(
int
n
)
{
static
size_t
cnt = 0;
//size_t cnt = 0;輸出答案0,1,2,3,。。。9;
cnt +=
n
;
n
;
return
cnt;
}
int
main()
main()
{
size_t
i;
for
(i = 0;i != 10;++i)
{
cout<<add(i)<<endl;
}
return
0;
}
總結
以上是生活随笔為你收集整理的笔记:C++学习之旅---try语句和异常处理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: u盘拆闪存颗粒-(u盘拆闪存颗粒怎么拆)
- 下一篇: 一键部署十个服务脚本--可拆分---ja