我对异常处理的理解很差(即,如何为自己的目的自定义 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++ 异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!