Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to throw a C++ exception

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: 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?

like image 391
Terry Li Avatar asked Dec 12 '11 20:12

Terry Li


People also ask

How do you throw an exception?

Throwing an exception is as simple as using the "throw" statement. You then specify the Exception object you wish to throw. Every Exception includes a message which is a human-readable error description. It can often be related to problems with user input, server, backend, etc.

What is an exception C?

Advertisements. An exception is a problem that arises during the execution of a program. A C++ exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero. Exceptions provide a way to transfer control from one part of a program to another.

How do you throw an exception in C++ class?

An exception in C++ is thrown by using the throw keyword from inside the try block. The throw keyword allows the programmer to define custom exceptions. Exception handlers in C++ are declared with the catch keyword, which is placed immediately after the try block.

What is throw in exception handling C#?

In c#, the throw is a keyword, and it is useful to throw an exception manually during the execution of the program, and we can handle those thrown exceptions using try-catch blocks based on our requirements. The throw keyword will raise only the exceptions that are derived from the Exception base class.


1 Answers

Simple:

#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...  } 

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( ... ) { }; 
like image 158
nsanders Avatar answered Sep 25 '22 23:09

nsanders