0

In python you can use:

try:
    #some code
except Exception as e:
    print e

And this will automatically catch any exception. Lets say you want to make a simple division in '#some code"...

variable = int(raw_input('Input: '))
result = 50/variable

Now, imagine somebody enters 0, or a letter, or even a string... As far as I know, since we used the generic exception catch, all of this will be taken care of and thus the code will jump to the except block, avoiding a crash.


In C++, you would have to check that the input is a number in one IF statement, and then check that it is not zero in another one, and if that's the case, throw the corresponding exception/s.

int var = 0, result = 0;

try{
    cin >> var;

    if (var == 0)
        throw "Zero Division Error";

    result = 50/var;

}catch(...){
    //exception handling code
}

All of this, (although untidy, and a bad practice), could have been done simply with pure IF-ELSE statements, without the try-catch block. However, in C++, should any unexpected exception occur, you are done. You have to manually take care of every exception, adding throw statements for every possible case, whereas in python, this is done automatically for you, and it even tells you what went wrong, and what kind of exception your generic variable 'e' caught.


So the question is:
Is there a way to write a try-catch block in whatever version of C++, that automatically takes care of any exception and assign it to a generic variable for you to print?

Because if there is not, I don't see the purpose of using the try-catch structure, other than making your code look tidy and more organized (same with the switch statement).

J3STER
  • 1,027
  • 2
  • 11
  • 28
  • 2
    Note that exceptions in C++, if thrown, are expensive. It's really not good practice to use them for simple input validation, only use them for truly *exceptional* events. – Some programmer dude Jan 25 '17 at 01:09
  • Also note that in most cases when an exception is thrown that isn't caught, it usually means there is an unrecoverable problem, and as such the simplest solution is to terminate. – Some programmer dude Jan 25 '17 at 01:15
  • Many actions that are exceptions in Python (such as division by 0) are not exceptions in C++. So, the answer to your question is probably **no**. – DYZ Jan 25 '17 at 01:24
  • Using `except Exception` is a very bad practice, and *not* what you should be doing in this case. If you are anticipating a `ZeroDivisionError` or maybe a `TypeError`, then you should explicitely handle `except (ZeroDivisionError, TypeError) as e:` – juanpa.arrivillaga Jan 25 '17 at 01:47

2 Answers2

3

Is there a way to write a try-catch block in whatever version of C++, that automatically takes care of any exception and assign it to a generic variable for you to print?

Yes if you follow the practice of only throwing exceptions of class type derived publicly from std::exception and overridding the what() method so that it returns a string with some appropriate error message. Any exception can then be handled with:

try {
    // ...
} catch (std::exception& e) {
    std::cerr << e.what() << std::endl;
}

For example, you could write an exception class like this:

class divide_error : public std::exception {
    const char* what() const {
        return "division by 0";
    }
};

The question of what exactly exceptions are good for in C++ is more opinion-based and has been covered elsewhere. See When and how should I use exception handling?

Community
  • 1
  • 1
Brian Bi
  • 111,498
  • 10
  • 176
  • 312
0

Regarding the fact that high level languages like python "automatically" detect exceptions, it all lies upon the fact that everything is an object (even simple ints and chars), and every operator is overloaded accordingly, so, for example, if you try to divide by zero, the interpreter (as opposed to C++'s compiler which simply does the appropriate bit wise operations, making it faster but more basic) takes the operation as a whole predefined method, and executes it accordingly. The important thing is that Inside Those methods predefined by python itself, there already are all the required checks that raise the corresponding exceptions.

If you take the time to overload everything and make sure that every variable you treat is actually an object, and all its methods and operators do the all corresponding checking, throwing a generic exception (that is making sure to define a default generic exception class, derived from the std::exception class, and overriding the corresponding methods to achieve your desired result, just like @Brian said) if necessary, you can achieve practically the same result.

  • 2
    Ohhh, actually, that makes a lot of sense. However I would like to know if there already is an API to simplify that – J3STER Jan 25 '17 at 03:34
  • 1
    I don't think so, since it is too complex to overload every basic feature c++ has to offer from scratch, thats why if you need a somewhat automatic try-catch structure, you should do the appropriate overloading and overriding yourself, taking care just about what you need, instead of redoing the whole language :P –  Jan 25 '17 at 03:36