英文:
Do we have a concept of checked and unchecked exceptions in Python?
问题
我的一位在JAVA上工作的朋友问我如何在Python中处理已检查和未检查异常。我以前没有听说过这些术语,所以我在网上搜索了一下,想找出什么是已检查和未检查异常。但我没有找到与这种类型异常相关的任何信息。
> 在Python中是否有已检查和未检查异常的概念?如果没有,那么默认情况下所有的异常是已检查的还是未检查的?
提前感谢你!
英文:
One of my friends who works on JAVA asked me how do I handle checked and unchecked exceptions in Python. I haven't heard these terms before, so I googled around to find out what is checked and unchecked exception. I didn't find anything related to this kind of exception in Python.
> Do we have a concept of checked and unchecked exceptions in Python? If
> no, then by default all the exceptions are checked or unchecked?
Thank you in advance!
答案1
得分: 8
Checked exceptions在Python中并不存在。但是Python在异常类层次结构上有一些相似之处。以下是Java的结构:
在Java中,如果方法可能会抛出Exception
或从Exception
继承的任何类,但不包括RuntimeException
,则必须在方法签名中声明。这个规则被称为checked exceptions。它强制用户考虑这些异常,否则应用程序将无法编译。
在Python中,我们仍然有一个类似的概念,但没有强制执行。你可能听说过,使用裸的except语句是不好的风格,至少你应该选择捕获Exception
try:
foo()
except: # 不好!
bar()
try:
foo()
except Exception: # 稍微好一些!
bar()
这是因为在Python中,Exception
继承自BaseException
,而裸的except
会捕获一切。例如,你可能不希望捕获引发ctrl+c
的KeyboardInterrupt
。如果你使用裸的except:
,那么KeyboardInterrupt
会被捕获,但如果你使用except Exception:
,你将让其上浮并停止应用程序。这是因为KeyboardInterrupt
继承自BaseException
而不是Exception
,因此不会被捕获!
英文:
Checked exceptions are not a thing in Python. But Python does have some similarities in the exception class hierarchy. Here is the Java structure:
In Java you have to declare in the method signature if the method will throw an Exception
or any class that inherits from Exception
, but not the RuntimeException
. This rule is called checked exceptions.. it forces the user to consider them or the application will not compile.
In Python we still have a similar concept, but no enforcement. You may have heard before that it's bad style to do a bare except statement, and at the very least you should choose to catch Exception
try:
foo()
except: # bad!
bar()
try:
foo()
except Exception: # somewhat better!
bar()
This is because in Python Exception
extends from BaseException
and a bare except
will catch everything. For example, you probably don't want to catch ctrl+c
which raises a KeyboardInterrupt
. If you do a bare except:
, then KeyboardInterrupt
will be caught, but if you do a except Exception:
you will let this bubble up and stop the application. That is because KeyboardInterrupt
extends BaseException
and not Exception
and therefore wont be caught!
答案2
得分: -1
Java有检查和非检查异常,因为Java是一种编译型编程语言,检查异常在编译时出现。在Python中,没有这样的异常,因为Python是一种解释型语言。
英文:
Java have checked and unchecked exceptions because Java is a complied programming language, checked exception comes in compiling. In python, there is no such exception because Python is an interpreted language.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论