問(wèn)題描述
我對(duì)異常處理的理解很差(即,如何為自己的目的自定義 throw、try、catch 語(yǔ)句).
I have a very poor understanding of exception handling(i.e., how to customize throw, try, catch statements for my own purposes).
例如我定義了一個(gè)函數(shù)如下:int compare(int a, int b){...}
For example, I have defined a function as follows: int compare(int a, int b){...}
我希望函數(shù)在 a 或 b 為負(fù)數(shù)時(shí)拋出一個(gè)帶有一些消息的異常.
I'd like the function to throw an exception with some message when either a or b is negative.
我應(yīng)該如何在函數(shù)定義中解決這個(gè)問(wèn)題?
How should I approach this in the definition of the function?
推薦答案
簡(jiǎn)單:
#include <stdexcept>
int compare( int a, int b ) {
if ( a < 0 || b < 0 ) {
throw std::invalid_argument( "received negative value" );
}
}
標(biāo)準(zhǔn)庫(kù)附帶了一個(gè)很好的內(nèi)置異常對(duì)象你可以扔.請(qǐng)記住,您應(yīng)該始終按值拋出并按引用捕獲:
The Standard Library comes with a nice collection of built-in exception objects you can throw. Keep in mind that you should always throw by value and catch by reference:
try {
compare( -1, 3 );
}
catch( const std::invalid_argument& e ) {
// do stuff with exception...
}
您可以在每次嘗試后使用多個(gè) catch() 語(yǔ)句,因此您可以根據(jù)需要分別處理不同的異常類型.
You can have multiple catch() statements after each try, so you can handle different exception types separately if you want.
你也可以重新拋出異常:
You can also re-throw exceptions:
catch( const std::invalid_argument& e ) {
// do something
// let someone higher up the call stack handle it if they want
throw;
}
并捕獲不分類型的異常:
And to catch exceptions regardless of type:
catch( ... ) { };
這篇關(guān)于如何拋出 C++ 異常的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!