關於c++的異常檢測的關鍵字主要有3個,分別是throw,try,catch。它們的作用如下:
throw用於丟擲錯誤,throw invalid_argument("can't open file");
try用於嘗試執行含有丟擲錯誤的**;
catch用於捕獲對應型別的錯誤物件,catch (invalid_argument& e),由於包含在中的錯誤型別是多型的,可以通過向上轉型的方式,捕獲更多不同型別的錯誤物件。比如catch (exception& e)可以捕獲invalid_argument,和runtime_error型別的錯誤物件。
關於錯誤丟擲的readfile函式如下所示:
在上面的**中,通過執行if(ifstr.fail())來判斷是否讀取檔案發生錯誤;通過執行if(ifstr.eof())來判斷是否讀取檔案異常退出。void readfile(const string& filename, vector& vec_str)
while(getline(ifstr, mystr))
if(ifstr.eof()) ifstr.close();
else
}
程式的try,catch部分寫在了主函式裡,如下所示:
由於exception是invalid_argument和runtime_error的基類,而且是變數引用的形式,所以可以捕獲invalid_argument和runtime_error型別的錯誤物件。int main()
catch(const exception& e)
readvector(vec_str);
}
如果需要編寫自己定義的異常類,主要只需要寫兩個函式,一是建構函式,一是what函式,如下:
其中,c_str表示c型別的字串,返回型別為cosnt char*。class fileerror: public exception
; virtual const char* what() const noexcept override
private:
string error_msg;
};
程式的所有**如下:
#include #include #include #include #include using namespace std;
class fileerror: public exception
; virtual const char* what() const noexcept override
private:
string error_msg;
};void readfile(const string& filename, vector& vec_str)
if(ifstr.fail())
while(getline(ifstr, mystr))
//~ if(ifstr.eof()) ifstr.close();
//~ else
//~
}void readvector(const vector& vec_str)
}int main()
catch(const fileerror& e)
catch(...)
readvector(vec_str);
}
以乙個閏年檢測程式為例的非法字元異常輸入檢測
閏年 閏年 leap year 是為了彌補認為曆法規定造成的年度天數與地球實際公轉週期的時間差而設立的。補上時間差的年份為閏年。簡單來說,置潤法則是 四年一閏,百年不閏,四百年再閏。即規定公曆年份是整百數的,必須是400的倍數才是閏年,不是400的倍數的就是平年。例如 1950 2050年間的閏年 ...
自定義異常練習(以銀行的存款取款為例)
package com.zidingyi public class newexception extends exception package com.zidingyi public class bank public void setyue double yue 成員方法 存錢 public d...
初探xml(以Mybatis的配置檔案為例)
第一行 這是xml的宣告 宣告了xml版本號和編碼 doctype 這個標籤作為一種標準通用標記語言的文件型別宣告,它的目的是要告訴標準通用標記語言解析器,它應該使用什麼樣的文件型別定義 dtd 來解析文件。這個標籤有三種寫法 我們這裡碰到的寫法叫做公共的外聯文件型別定義 使用公共識別符號 格式如下...