[英]Why would you create your own custom exception class?
我是C ++的新手,我想了解為什么您要創建自己的自定義異常類。
我一直在閱讀一些書籍和在線材料,它們在其中指定您可以創建自己的異常類,但是它們沒有解釋為什么以及何時要創建異常類。
你為什么要創建這個課程
class ArrayException
{
private:
std::string mError;
public:
ArrayException(std::string error) : mError(error) {}
const char *GetError()
{
return mError.c_str();
}
};
在我們的自定義IntegerArray
容器類中
if(index < 0 || index >= GetLength())
{
throw ArrayException("Invalid index");
}
內部main()
int main()
{
IntArray arr;
try
{
arr[6] = 100;
}
catch(ArrayException error)
{
std::cout << "An exception has been caught! " <<
error.GetError() << std::endl;
}
return 0;
為什么不使用
if(index < 0 || index >= GetLength())
{
throw "Invalid index";
內部main()
int main()
{
IntArray arr;
try
{
arr[6] = 100;
}
catch(const char *error)
{
std::cout << "An exception has been caught! " << error <<
std::endl;
}
return 0;
}
這是本課程中的示例之一。
僅以通常的方式拋出並捕獲異常不是一件容易的事嗎? 我希望我的問題有意義,因為英語不是我的母語。
為什么要創建自己的自定義異常類?
因為可以通過類捕獲異常,並且自定義類允許捕獲器執行自定義catch子句。 例:
while(true) {
try {
do_something();
} catch(custom_recoverable_exception& e) {
// assume that we know about this exception; why it is thrown
// and how to fix the problem in case it is thrown
recover(e.custom_data);
continue; // try again
} catch(std::exception& e) {
// some other exception; we don't know how to recover
diagnose_exception(e); // write to a log or to standard output
throw; // re-rhrow: Maybe the caller of this function knows how to proceed
}
proceed_with_the_loop();
僅以通常的方式拋出並捕獲異常不是一件容易的事嗎?
拋出和捕獲自定義類的對象是正常的方法。
如果您要說的話,為什么不拋出一個指向字符串的指針:因為如果所有拋出的對象都具有相同的類型,那么您將無法以不同的方式處理一個拋出。
請注意,習慣上是從std::exception
(或其子類之一)繼承自定義異常類,以便函數的用戶可以在不需要特殊處理的情況下以與標准異常相同的邏輯來處理自定義異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.