Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the C++ Standard allow the addition of two integers (fundamental type int) to throw a C++ exception?

Does the Standard allow this?

I don't think it does. Someone does. I need intelligent people to prove him wrong.

like image 869
rubenvb Avatar asked May 19 '13 15:05

rubenvb


People also ask

Is there exception handling in C?

The C programming language does not support exception handling nor error handling. It is an additional feature offered by C. In spite of the absence of this feature, there are certain ways to implement error handling in C. Generally, in case of an error, most of the functions either return a null value or -1.

What is throwing an exception in C Plus Plus?

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.

Which data types Cannot be thrown as exceptions in a C++ program?

But which data type can't be thrown as exception in C++? Abstract types, (pointers to) incomplete types and types without accesible copy/move constructor.

How many types of standard exceptions are in C Plus Plus?

There are two types of exceptions: a)Synchronous, b)Asynchronous (i.e., exceptions which are beyond the program's control, such as disc failure, keyboard interrupts etc.). C++ provides the following specialized keywords for this purpose: try: Represents a block of code that can throw an exception.


2 Answers

Yes, it does. The overflow of signed integers is undefined behavior, so anything could happen (including an exception being thrown).

As a side note, I must say this is unlikely to happen (yet definitely possible) for most implementations; as the C++11 Standard mentions in a note to paragraph 5/4:

If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined. [ Note: most existing implementations of C++ ignore integer overflows. Treatment of division by zero, forming a remainder using a zero divisor, and all floating point exceptions vary among machines, and is usually adjustable by a library function. —end note ]

As hvd mentions in the comments, however, some implementations allow to provide custom handlers for integer overflow, and those handlers may throw.

like image 177
Andy Prowl Avatar answered Sep 20 '22 21:09

Andy Prowl


The rule of thumb is anything that is can be written in C cannot and should not throw an exception...

Therefore, it wouldn't.

As Andy says, this behavior is undefined so anything can happen. In theory the computer could also go make you a cup of coffee and take your dog for a walk. However if you were in a job interview, I would suggest you tell them no :)

like image 43
Dory Zidon Avatar answered Sep 18 '22 21:09

Dory Zidon