Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Exception Handling

So I was writing some code and I noticed that apart from syntactical, type, and other compile-time errors, C++ does not throw any other exceptions. So I decided to test this out with a very trivial program:

#include<iostream>

int main() {
    std::count<<5/0<<std::endl;
return 1
}

When I compiled it using g++, g++ gave me a warning saying I was dividing by 0. But it still compiled the code. Then when I ran it, it printed some really large arbitrary number. When I want to know is, how does C++ deal with exceptions? Integer division by 0 should be a very trivial example of when an exception should be thrown and the program should terminate.

Do I have to essentially enclose my entire program in a huge try block and then catch certain exceptions? I know in Python when an exception is thrown, the program will immediately terminate and print out the error. What does C++ do? Are there even runtime exceptions which stop execution and kill the program?

like image 810
user1413793 Avatar asked Jun 07 '12 04:06

user1413793


1 Answers

There are runtime exceptions, but not everything that's "wrong" results in a runtime exception being thrown. For example, acccessing an array out of bounds or dereferencing a null pointer is simply "undefined behaviour" - meaning anything at all can happen. Division by zero also falls into the "undefined" category.

The rationale for some operations resulting in "undefined behaviour" rather than an exception is efficiency. Suppose an out-of-bounds array access required an exception to be thrown. Then the compiler would have to generate code for each array access to checks whether it's out of bounds, and if so, throw an exception. That's a lot of checking, most of which is unnecessary. Instead, what compilers do is just generate the instruction for the element access assuming it is within bounds. If it happens to be out of bounds, then whatever happens (e.g. segmentation fault) happens. If you want a check to be performed, you can always code it explicitly.

This makes C++ more powerful than languages that always do checks (e.g. Java or python) because you can choose when you want a check done, and when you don't. (On the other hand, it makes C++ less safe than Java or python. It's a trade-off).


As for what happens when an exception is thrown but not caught anywhere, typically compiler implementations will print an error message containing the exception's what(). In your example that's not applicable because no runtime exception is being thrown.

like image 159
HighCommander4 Avatar answered Sep 21 '22 07:09

HighCommander4