异常处理指南 - Python与Java [英] Exception Handling guideline- Python vs Java

查看:102
本文介绍了异常处理指南 - Python与Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是原始的Java开发人员,对于我来说,在Java中检查异常显然/很容易让我决定抓住或将其抛出给调用者来处理。那么它是Python,没有被检查的异常,所以在概念上,没有什么会强制你处理任何东西(根据我的经验,你甚至不知道什么异常可能被抛出,而不检查文档)。我从Python家庭听到很多,在Python中,有时候你最好只是在运行时失败,而不是试图处理例外。



有人可以给我一些关于:


  1. Python异常处理的准则/最佳做法是什么?


  2. 在这方面,Java和Python有什么区别?



解决方案

好的,我可以尝试一个答案,我会保持中立,因为它可以...(注意:我已经做了专业的Python几个月,但我远离掌握完整的语言)


  1. 准则是免费的;如果你来自Java的背景,你一定会花更多的时间比大多数Python开发者在那里寻找关于什么被抛出的文档,并且有更多的尝试 / 除了 / finally 比在常规python代码中找到的内容。换句话说:做什么适合你。


  2. 除了可以在任何地方抛出的事实之外,Python还有多异常捕获可用于Java 7),(有点相当于Java 7的试用资源),您可以有多个块(像Java可以 catch 多次)等等。另外,我没有知道如何命名异常的真正惯例,所以如果您看到 SomeError ,则可能会被愚弄,这可能是Java开发人员将其视为检查的异常而不是错误



I am original Java developer, for me, checked Exception in Java is obviously/easy enough for me to decide to catch or throw it to the caller to handle later. Then it comes Python, there is no checked exception, so conceptually, nothing forces you to handle anything(In my experience, you don't even know what exceptions are potentially thrown without checking the document). I've been hearing quite a lot from Python guys that, in Python, sometimes you better just let it fail at runtime instead of trying to handle the exceptions.

Can someone give me some pointers regarding to:

  1. what's the guideline/best practice for Python Exception Handling?

  2. what's the difference between Java and Python in this regard?

解决方案

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.

这篇关于异常处理指南 - Python与Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆