Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are using exceptions more acceptable in python than javascript

You can replace "javascript" with other languages here. Basically what I've found from reading is that python actively encourages the use of exceptions and a series of if tests to manage code. Often readability is cited as well as cleaner looking code when 'duck-typing'

However, often when working in javascript or some other languages, it seems that best practices suggest trying to 'code defensively' and cover as much as you can in if statements and return types in order to avoid using exceptions. The reason most often cited is because exceptions are a very expensive operation.

Here's an example: https://stackoverflow.com/a/8987401/2668545

  • Does python face the same exceptions cost as javascript and the best practices are such because there's more emphasis about readability/debuggability than performance?
  • Does python have a different way of handling exceptions than javascript or other languages that don't recommend using exceptions?
  • Am I misinterpreting the advice?
  • Or is it something else?
like image 415
ThinkBonobo Avatar asked Feb 03 '26 19:02

ThinkBonobo


1 Answers

My take on this would be that though Python is a dynamically typed language, it is strongly-typed at the same time, see the explanation here. This means that if something goes wrong deep down the call hierarchy (like trying to convert an empty string to an integer, division by zero, etc.), the interpreter raises an interrupt that bubbles up the call graph.

Javascript and many other interpreted languages tend to gloss such things over and continue silently computing (rubbish) as long as possible. Essentially, the programmer has to defend against Javascript itself.

It is thus consistent when a user-defined Python module behaves in the same way as the standard library modules and the interpreter itself: achieve the expected result or raise an exception.

The advantages are:

  • Improved readability: the expected sequence of actions is not mixed with error handling.
  • Extra polymorphism. It can be possible to pass any object as a function argument, and things will work out if the object has the properties/members used by the function. The programmer writing the function does not have to know in advance the exact type of the argument (dynamic typing). If something goes wrong, there will be a call trace to investigate. Defensive checks are likely to be too restrictive and not 100% bullet-proof at the same time.

The considerations of readability and extensibility are probably more important than the ones of performance.

like image 74
Mike Bessonov Avatar answered Feb 06 '26 09:02

Mike Bessonov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!