Reputation: 163
I honestly searched and tried to implement try - catch mechanism in C++, but I failed: I don't have enough experience yet. In Android there is a convenient way to catch general exceptions, whether it's a division by zero or an array out-of-bounds, like
int res;
int a=1;
int b=0;
try{res = a/b;}
catch(Exception e)
{
int stop=1;
};
Works fine, program does not crash.
Could you please tell me how to make an universal exceptions interceptor in C++, if possible.
Upvotes: 1
Views: 1205
Reputation: 11438
C++ has a diverse range of error handling for different problems.
Division by zero and many other errors (null pointer access, integer overflow, array-out-of-bounds) do not cause an exception that you can catch.
You could use tools such as clang's undefined behavior sanitizer to detect some of them, but that requires some extra work on your part, and comes with a performance hit.
The best way in C++ to deal with prevention of a division by zero, is to check for it:
int res;
int a=1;
int b=0;
if (b == 0)
{
int stop=1;
}
else
{
res = a/b;
}
See also the answers to this other very similar question.
Upvotes: 3