exception::what()用於獲取字符串標識異常。此函數返回一個空終止的字符序列,該序列可用於標識異常。以下是相同的語法:
頭文件:
#include<exception>
用法:
virtual const char* what() const throw();
返回:函數std::what()返回一個空終止的字符序列,用於識別異常。
注意:要使用std::what(,應設置適當的try和catch塊。
下麵的程序可以更好地理解std::what(的實現:
程序1:
// C++ code for exception::what()
#include <bits/stdc++.h>
using namespace std;
struct gfg:exception {
const char* what() const noexcept
{
return "GeeksforGeeks!! "
"A Computer Science"
" Portal For Geeks";
}
};
// main method
int main()
{
// try block
try {
throw gfg();
}
// catch block to handle the errors
catch (exception& gfg1) {
cout << gfg1.what();
}
return 0;
}
輸出:
GeeksforGeeks!! A Computer Science Portal For Geeks
程序2:
// C++ code for exception::what()
#include <bits/stdc++.h>
using namespace std;
struct geeksforgeeks:exception {
const char* what() const noexcept
{
return "Hey!!";
}
};
// main method
int main()
{
// try block
try {
throw geeksforgeeks();
}
// catch block to handle the errors
catch (exception& gfg) {
cout << gfg.what();
}
return 0;
}
輸出:
Hey!!
參考:http://www.cplusplus.com/reference/exception/exception/what/
相關用法
- C++ std::less用法及代碼示例
- C++ cin get()用法及代碼示例
- C++ iswprint()用法及代碼示例
- C++ std::is_copy_constructible用法及代碼示例
- C++ iswgraph()用法及代碼示例
- C++ std::bit_xor用法及代碼示例
- C++ std::remove_const用法及代碼示例
- C++ std::is_trivially_assignable用法及代碼示例
- C++ basic_istream::get()用法及代碼示例
- C++ std::has_virtual_destructor用法及代碼示例
- C++ cauchy_distribution a()用法及代碼示例
- C++ ratio_equal()用法及代碼示例
- C++ std::to_address用法及代碼示例
- C++ std::is_nothrow_destructible用法及代碼示例
- C++ std::remove_volatile用法及代碼示例
- C++ std::is_trivially_move_assignable用法及代碼示例
注:本文由純淨天空篩選整理自bansal_rtk_大神的英文原創作品 exception::what() in C++ with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。