So, I wrote the code, and I noticed that in addition to syntax, types, and other compile-time errors, C ++ does not throw any other exceptions. So I decided to test this with a very simple program:
#include<iostream> int main() { std::count<<5/0<<std::endl; return 1 }
When I compiled it with g ++, g ++ gave me a warning that I was divisible by 0. But he still compiled the code. Then, when I ran it, it printed a very large arbitrary number. When do I want to know how C ++ handles exceptions? Integer division by 0 should be a very trivial example of when an exception should be thrown and the program should terminate.
Should I essentially wrap my entire program in a huge try block, and then catch some exceptions? I know in Python, when an exception is thrown, the program will immediately stop and print the error. What does c ++ do? Are there even runtime exceptions that stop execution and kill the program?
, , "" , . , - " undefined" - - . "undefined".
, "undefined", , . , . , , , , . , . , , . , , (, ). , .
++ , , (, Java python), , , . ( , ++ , Java python. ).
, , , , , what(). , .
what()
, . , out_of_range, vector::at.
out_of_range
vector::at
undefined (++ 0x Β§5.6/4):
/% , .
, , , "- " segfault.
++ , ++. (, )
, , ++ ( Undefined ). , . - ( , - ), . , .
The best you can do is check the error condition (divisor is zero) yourself and explicitly throw an exception in such cases.
EDIT: To respond to a comment
class A { public: void f() { int x; //For illustration only int a = 0; if(a == 0) throw std::runtime_error( "Divide by zero Exception"); x=1/a; } A() { try { f(); } catch(const std::runtime_error& e) { cout << "Exception caught\n"; cout << e.what(); } } };
Visual C ++ correctly designates this as dividing by zero error. So if it does not compile, then there is no question of running it.