debugcppCritical
How to throw a C++ exception
Viewed 0 times
exceptionthrowhow
Problem
I have a very poor understanding of exception handling(i.e., how to customize throw, try, catch statements for my own purposes).
For example, I have defined a function as follows:
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?
For example, I have defined a function as follows:
int compare(int a, int 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?
Solution
Simple:
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:
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:
And to catch exceptions regardless of type:
#include
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...
}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( ... ) { };Code Snippets
#include <stdexcept>
int compare( int a, int b ) {
if ( a < 0 || b < 0 ) {
throw std::invalid_argument( "received negative value" );
}
}try {
compare( -1, 3 );
}
catch( const std::invalid_argument& e ) {
// do stuff with exception...
}catch( const std::invalid_argument& e ) {
// do something
// let someone higher up the call stack handle it if they want
throw;
}catch( ... ) { };Context
Stack Overflow Q#8480640, score: 551
Revisions (0)
No revisions yet.