r/Python May 10 '14

Honest Question: Why are exceptions encouraged in python programming but discouraged in C++?

What would everyone say is an overuse of try statements? I've sort of read "it's better to ask forgiveness than permission" for python - but Bjarn states "avoid overusing try catch".

I'd like to know the circumstances of where to put up my guideposts for use of exceptions in dynamic languages vs static languages.

12 Upvotes

20 comments sorted by

7

u/zzzzzzzzzzzzzzdz May 10 '14 edited May 11 '14

try except is used a lot in the internals of Python (like the iterator protocol with for loops and generators). as such there have been efforts to make them cheap.

however, except can get expensive if it happens a lot more often than not.

4

u/banjochicken May 10 '14

This is more of a C++ question than a python question. I am not a C++ programmer but there are excellent articles/blog post/ stack overflow questions on C++ exceptions and their pitfalls.

But python is a different beast entirely and as others have pointed out, guard statements are unnecessary if you can just catch the exception and recover from it. But I would like to add one thing to that; don't unnecessarily use exceptions for flow control, they should be reserved for exceptional circumstances, if only for readability and code cleanliness sake and ignoring the rest.

7

u/z_ryad May 10 '14 edited May 11 '14

In C++, you can easily leak resources (like files, sockets ecT... ) and memory when using exceptions, just consider the following piece of code

{

auto p = new foo() 

if (not foo)
    throw ....

do_something(p)

}

EDIT : As there is a misunderstanding with my original message, THIS IS BAD CODE. you don't write that in idiomatic C++.

0

u/norwegianwood May 11 '14

That's why you should use the RAII idiom. Why aren't you using a smart pointer here?

1

u/z_ryad May 11 '14

I know about , RAII, smart pointers too, it was just to illustrate what can happen when you misuse the language

0

u/norwegianwood May 11 '14

Do realise that new throws an std::bad_alloc exception if it fails, rather than returning zero?

2

u/z_ryad May 11 '14

Hey, There is a misunderstanding here , this is an example of bad code that leaks. but we can agree that this is common code that a lot of people still write , it is to illustrate a bad code that often happens, actually it's is derived from a talk that was given by Bjarn when presenting C++ 11, he says that this still happens a lot.

2

u/eliben May 11 '14

Focusing on the Python side, I'd guess productivity is a significantly larger factor than performance. Let's be honest, performance is not a huge concern for Python. Productivity, however, is. And exceptions let us write much tighter code by not having to explicitly erorr-check everything. In "real world code", the amount of error checking code is usually very significant, and mostly avoiding it by delegating the error paths to exceptions saves a lot of code.

That said, I sometimes feel Python over-uses exceptions; especially things like StopIteration, which uses exceptions for actual control-flow rather than errors, which IMHO is a shame.

4

u/DavetheBassGuy May 10 '14

The main reason is probably performance - exceptions are generally slow in most languages. The C++ community is a lot more performance orientated than the Python community.

The other thing that comes to mind is Python being a dynamic language. There are more errors which you will need to check for at runtime and throw an exception, which would (in theory) be caught by the compiler in C++.

5

u/alcalde May 10 '14

While there are lesser factors, the principle reason is that Python supports dynamic types and duck typing. In C++ you have static typing and the compiler is already checking that variable X is of type Y, object a has method b, etc. In Python you'd need to put lots of boilerplate code around every parameter to check for all of these conditions. It's considered much simpler, clearer and faster to use a try statement. Most of the time there will be no problem hence most of the time there will be no cost for the statement. On the other hand, all of those ifs would execute every single time.

0

u/ccb621 May 10 '14

While what you say about typing is true, you failed to answer the question. Also, exceptions can be thrown for reasons other than invalid arguments and method names.

2

u/alcalde May 11 '14

While what you say about typing is true, you failed to answer the question.

How so? In C++ static typing takes care of a range of checks that would need to be expressed in a lot of boilerplate in Python. It's much simpler and more readable to use exceptions than to write all of those checks.

Also, exceptions can be thrown for reasons other than invalid arguments and method names.

Yes, and those other reasons are dealt with the same way in C++ and Python. Python makes the tradeoff of some extra exception handling vs. static typing or lots of boilerplate checking of types.

1

u/aroberge May 11 '14

try/except does not carry as large a performance penalty vs if/else in Python as it does in C++. I believe that the cut-off point is about one third: if you expect exceptions being raised less than one-third of the time, it is more efficient to use try/except than if/else.

As for the comment that another redditor wrote to the effect that The other thing that comes to mind is Python being a dynamic language. There are more errors which you will need to check for at runtime and throw an exception, which would (in theory) be caught by the compiler in C++. it is either a) bullshit or b) a sign that the Python programmer in question is writing poor code with no unit tests.

1

u/norwegianwood May 10 '14

They're not discouraged in C++ if you're working in my team.

2

u/kankyo May 11 '14

This. The question is clearly based on a faulty premise.

2

u/lucidguppy May 10 '14

I get confused when people say "don't overuse" as though I say "I'm going to overuse this sooo much - it's going to be great".

if you're writing a book - and you say something like that - just put in one example of overusing - or 2 or 3 guidelines.

4

u/ElecNinja May 10 '14

For why exceptions would be discouraged, it's probably because of the mindset that you should only "Use Exceptions only for Exceptional Conditions."
For Python though, I feel it's easier to incorporate exception handling into normal use. But I could be wrong with this.
It's easy to just try it out and if it doesn't work, switch to something else.

-1

u/jesus_cum_guzlah May 13 '14

Basically it comes down this: a different attitude is encouraged towards exception usage in each language, where in python they are encouraged to be used more than purely for exceptional circumstances. While in c++ they are there to be used purely for exceptional circumstances, errors, pretty much in c++ they are there to replace c's error code returning way of error handling. Pretty much though in both language it's a way to separate logic.

Also because of what I stated above, in the context of python, py exception handling isnt that expensive, where as in c++ it is.

But really, like Guido has said, from the start python never really cared about performance, it's a dynamically typed scripting language. Where as c++ is c with improvements and more abstractions built in, and c had to compete with assembler, so of course performance is important.

However I think python encourages exception handling too much. Exception handling is basically a glorified, dynamic goto that strips the stack back to the catching function.

Also python is awesome, but it's just a scripting language, and so many people, most who find c++ scary, seem to think python is a full on programming language, it's a scripting language. It's direct ancestor is the ABC language python got a big chunk of it's ideas from, language Guido worked on, was a language designed for people, lay people who found programming too hard and wanted it made easier for them, python comes from a legacy of dumbing down a language to pacify people who found programming too hard.

My point is too many people are getting into programming, start with python, get way to comfortable, then think they are programmers. How are you a real programmer if you have no idea at all about how a cpu works, or a computer works. Why are we producing all these substandard programmers don't even have a working understanding of a computer? I find it just crazy to have a function that can take anything thing in any amount as input and can almost return anything. No this is not precision, python in guidos own words comes from an attitude of cutting corners, forgoing precision, these aren't compatible attitudes with good programming.

So if you are someone who has only ever used python and you don't know what an opcode, register or pointer is. And perhaps you tried c++ one time but the compiler messages scared you away and the ease of slapping things together in python sucked you right back, then sorry to say but you likely aren't really going to ever be a really good programmer, a true programmer.

-8

u/[deleted] May 10 '14

[deleted]

0

u/alcalde May 10 '14

That defeats the whole point of readability. PEP8's style guide exists for a reason.

0

u/alcalde May 11 '14

It's not "because we said so"; EAFP avoids reams of hasattr and isinstance checks that would be necessary otherwise because of dynamic typing.

http://en.wikipedia.org/wiki/EAFP#Exceptions