Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

简单的Python捕获异常! #4

Open
Lucifer-ww opened this issue May 3, 2020 · 1 comment
Open

简单的Python捕获异常! #4

Lucifer-ww opened this issue May 3, 2020 · 1 comment
Labels

Comments

@Lucifer-ww
Copy link
Owner

程序未免会发生异常,于是想出了一个招!叫捕获异常

Python的异常很多,比如我想运算1/'qqq',那么程序会抛出TypeError,说明1和'qqq'不是一个类型(Type),无法运算!

于是我们需要一个try语句来尝试1/'qqq',这样程序是允许的,然后跟上[except],其实类似[else]的含义,就是如果try成功执行,就不走[except]了

格式:

try:
    尝试语句
except 异常类型:
    异常了怎么办可以多重except就是侦测多个异常

实例:

n = 100
try:
    print(100 / 'QQQ')
except TypeError as te:
    print("TypeError!")
    print(te)
except ValueError as ve:
    print("ValueError!")
    print(ve)

其中ve和te你不用管,这是输出异常信息

最后输出:

TypeError!
unsupported operand type(s) for /: 'int' and 'str'
@Lucifer-ww
Copy link
Owner Author

挺不错的吧

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant