Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Throwing exceptions, use 'new' or not?

Is it proper to use throw new FoobarException(Baz argument); or throw FoobarException(Baz argument);?

When catching I always use catch(FoobarException& e) "just in case" but I never could find a solid answer whether I had to use new or not in C++ (Java definitely) or if it was just a preference of the programmer.

like image 804
Casey Avatar asked Jul 23 '11 16:07

Casey


People also ask

Does new throw an exception?

The nothrow constant value is used as an argument for operator new and operator new[] to indicate that these functions shall not throw an exception on failure but return a null pointer instead.

Does C++ throw new exception?

Throwing exceptions from C++ constructors Since C++ constructors do not have a return type, it is not possible to use return codes. Therefore, the best practice is for constructors to throw an exception to signal failure. The throw statement can be used to throw an C++ exception and exit the constructor code.

Can you throw exceptions in C?

C doesn't support exceptions. You can try compiling your C code as C++ with Visual Studio or G++ and see if it'll compile as-is. Most C applications will compile as C++ without major changes, and you can then use the try... catch syntax.

Which is the exception thrown by new operator?

Definition. std::bad_alloc is a type of exception that occurs when the new operator fails to allocate the requested space. This type of exception is thrown by the standard definitions of ​operator new (declaring a variable) and operator new[] (declaring an array) when they fail to allocate the requested storage space.


1 Answers

Exceptions in C++ should be thrown by value, and caught by reference.

So this is the proper way:

try {     throw FoobarException(argument); } catch( const FoobarException &ex ) {     cout << ex.what() << endl; } 

Don't throw an exception created with new, since who's responsible for deleting it is not well-defined. In addition, performing allocations during error handling can throw another exception, obscuring the original problem.

You don't have to catch by const reference (non-const will work fine), but I like doing it anyway. You should however always by reference (not by value) to catch the exception polymorphically. If you don't, the exception's type could be sliced.

like image 107
Sven Avatar answered Sep 18 '22 22:09

Sven