1

When running some code I had written I was surprised to see that a function threw an exception that was not caught and so my code crashed. The thing is, Spyder never informed me that the function could even throw an exception.

Is there a setting somewhere that I have to turn on to be informed of this?

Aphyd
  • 193
  • 5
  • i had a similar question some time ago: https://stackoverflow.com/questions/32560116/how-to-list-all-exceptions-a-function-could-raise-in-python-3 . the short answer is: no, python will not inform you about exceptions; you have to rely on the documentation. – hiro protagonist Jul 20 '20 at 19:04
  • also type hints will not help with exceptions: https://stackoverflow.com/questions/44282268/python-type-hinting-with-exceptions – hiro protagonist Jul 20 '20 at 19:07
  • wait.... seriously? Python does not have a built in way to keep track of thrown exceptions? – Aphyd Jul 20 '20 at 19:08
  • no.... you can always have an `except Exception as e: ...` clause as the last of your `except` statements; that will catch everything that has not been caught by a more specialized exception. – hiro protagonist Jul 20 '20 at 19:21

1 Answers1

1

Python isn't Java. Your IDE will not warn you about uncaught exceptions, because Python's dynamic nature means that exceptions could be raised (or caught) almost anywhere and there's no amount of static analysis that'll work for every -- or even most -- cases. Often when you develop Flask or Django applications, you actually want exceptions to float all the way up to the "root" exception handlers.

Bottom line: No Python IDE is going to do this, and it would not be expected or considered generally desirable in Python programming.

Ken Kinder
  • 12,654
  • 6
  • 50
  • 70
  • Huh. Interesting. Probably just cause I mostly program in Java but I find it incredibly desirable to know when and how my program might crash, and to be able to handle that in some way. – Aphyd Jul 20 '20 at 19:35
  • Yeah. Your best bet is to read the docstring of the function you're calling for an explanation of what exceptions are likely to be raised. But ultimately with duck typing, it could be too dynamic. Suppose you write a function, "return a + b". That works for two strings. Or two ints. But not one string and one int, which will cause an exception, but not really an expected one. (BTW, if you're a Java programmer, you might checkout PyCharm. Spyder is nice and all, but PyCharm is the most popular and based on IntelliJ for Java!) – Ken Kinder Jul 20 '20 at 19:40
  • Ah yes that example highlights why the situation is different in python. And thanks, I'll check out PyCharm. I'm just using spyder because it came with anaconda – Aphyd Jul 20 '20 at 19:42