Python系列教程

在Python中如何捕获所有异常而不指定具体的错误类型

2025-10-26 3 0

简介 在Python中如何捕获所有异常而不指定具体的错误类型

在Python中,要捕获所有异常而不指定具体的错误类型,你有几种写法:

方法1:使用空的except语句

python

try:
    x = int(input('Enter the first number:'))
    y = int(input('Enter the second number:'))
    print(f"Result={x/y}")
except:
    print("An error occurred!")

方法2:使用Exception基类(推荐)

python

try:
    x = int(input('Enter the first number:'))
    y = int(input('Enter the second number:'))
    print(f"Result={x/y}")
except Exception:
    print("An error occurred!")

方法3:获取异常信息

python

try:
    x = int(input('Enter the first number:'))
    y = int(input('Enter the second number:'))
    print(f"Result={x/y}")
except Exception as e:
    print(f"An error occurred: {e}")

修正你的代码

python

try:
    x = int(input('Enter the first number:'))
    y = int(input('Enter the second number:'))
    print(f"Result={x/y}")
except:
    print("The second number can't be zero!")

推荐做法

我建议使用方法2或3,因为:

  • 空的except:会捕获所有异常,包括键盘中断(Ctrl+C)等系统异常

  • except Exception:只捕获程序层面的异常,不会干扰系统级别的异常

更完整的版本

python

try:
    x = int(input('Enter the first number:'))
    y = int(input('Enter the second number:'))
    print(f"Result={x/y}")
except ValueError:
    print("Please enter valid numbers!")
except ZeroDivisionError:
    print("The second number can't be zero!")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

这样既能处理预期的错误,也能捕获其他意外异常。


点赞 0

我的名片

网名:梦宇信息技术

职业:软件开发、Mes系统工程师

现居:福建省-福州市

QQ:703159

站点信息

  • 联系QQ:703159
  • 文章统计118篇文章
  • 标签总数6
  • 加我微信:扫码,加我微信