Exception Handling guideline- Python vs Java

断了今生、忘了曾经 提交于 2019-12-05 02:29:06

OK, I can try and give an answer which I'll keep as neutral as it can be... (note: I have done Python professionally for a few months, but I am far from mastering the language in its entirety)

  1. The guidelines are "free"; if you come from a Java background, you will certainly spend more time than most Python devs out there looking for documentation on what is thrown when, and have more try/except/finally than what is found in regular python code. In other words: do what suits you.

  2. Apart from the fact that they can be thrown anywhere, at any moment, Python has multi-exception catch (only available in Java since 7), with (somewhat equivalent to Java 7's try-with-resources), you can have more than one except block (like Java can catch more than once), etc. Additionally, there are no real conventions that I know of on how exceptions should be named, so don't be fooled if you see SomeError, it may well be what a Java dev regards as a "checked exception" and not an Error.

I'm not a Python dev, but I've done a quite bit of work in C#, which also doesn't have checked exceptions. Being a Java coder that took some getting used to. I personally still think checked exceptions are a nice feature, but opinions differ wildly (as you can see in some of the responses here).

There are quite a few articles online on why checked exceptions are(n't) a good idea (see this blog for one such opinion).

But regardless of your preference: the rule of thumb in Python and C# is to do essentially what you're already doing - test runs and reading the docs.

What I'd typically do in C# is have a 'catch-all' exception handler at the root of my program that makes sure any error is reported and the program exits cleanly, and then deeper in my code have more specific exception handlers for "known specific errors". So actually, not so different from how you'd work in Java, just a little more work to figure out where to put your specific handlers.

  1. Best practice is to handle appropriate exceptions in the appropriate place. Only you, as developer, can decide which part of your code should catch exceptions. This should become apparent with decent unit testing. If you have unhandled exceptions, they will show up.

  2. You already described the differences. At a more fundamental level, Java's designers think they know better than you how you should code, and they'll force you to write lots of it. Python, by contrast, assumes that you are an adult, and that you know what you want to do. This means that you can shoot yourself in the foot if you insist on so doing.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!