問題描述
我對異常處理的理解很差(即,如何為自己的目的自定義 throw、try、catch 語句).
I have a very poor understanding of exception handling(i.e., how to customize throw, try, catch statements for my own purposes).
例如我定義了一個函數如下:int compare(int a, int b){...}
For example, I have defined a function as follows: int compare(int a, int b){...}
我希望函數在 a 或 b 為負數時拋出一個帶有一些消息的異常.
I'd like the function to throw an exception with some message when either a or b is negative.
我應該如何在函數定義中解決這個問題?
How should I approach this in the definition of the function?
推薦答案
簡單:
#include <stdexcept>
int compare( int a, int b ) {
if ( a < 0 || b < 0 ) {
throw std::invalid_argument( "received negative value" );
}
}
標準庫附帶了一個很好的內置異常對象你可以扔.請記住,您應該始終按值拋出并按引用捕獲:
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...
}
您可以在每次嘗試后使用多個 catch() 語句,因此您可以根據需要分別處理不同的異常類型.
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( ... ) { };
這篇關于如何拋出 C++ 異常的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!