1

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.

tripleee
  • 175,061
  • 34
  • 275
  • 318
newman
  • 149
  • 10
  • Can [this](https://www.tutorialspoint.com/how-to-catch-all-the-exceptions-in-cplusplus) help ? – Scryper Apr 07 '22 at 07:57
  • 1
    `catch(...)` is about as "universal" as you'll get in terms of a catch-all, but it won't catch things like divide-by-zero, segfaults etc which are generally the responsibility of the programmer to avoid. – paddy Apr 07 '22 at 07:59
  • 4
    Division by zero or out-of-bounds array accesses (and many other things) do not throw C++ exceptions - they have undefined behaviour. It is the programmer's responsibilty to check before trying. – molbdnilo Apr 07 '22 at 08:01
  • @Scryper That link doesn't explain anything. The grammar of several sentences isn't even correct and aside from that basically all sentences are not-quite-right in content. – user17732522 Apr 07 '22 at 08:25
  • 1
    This gets confusing, because the OS claims that some errors are exceptions, but that's a different word from "exception" in C++. In C++ you can only `catch` something that you `throw`. If it doesn't say `throw` it's not an exception. – Pete Becker Apr 07 '22 at 13:41
  • did the provided answer help you? if so, please consider upvoting / accepting it. if not, feel free to comment on what aspect ia still unclear! – codeling Apr 16 '22 at 17:38

1 Answers1

3

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.

codeling
  • 11,056
  • 4
  • 42
  • 71