菜单
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

Python 教程

Python 主页 Python 简介 Python 入门 Python 语法 Python 注释 Python 变量 Python 数据类型 Python 数字 Python 类型转换 Python 字符串 Python 布尔值 Python 运算符 Python 列表 Python 元组 Python 集合 Python 字典 Python If...Else Python While 循环 Python For 循环 Python 函数 Python Lambda Python 数组 Python 类/对象 Python 继承 Python 迭代器 Python 多态 Python 作用域 Python 模块 Python 日期 Python 数学 Python JSON Python 正则表达式 Python PIP Python Try...Except Python 用户输入 Python 字符串格式化

文件处理

Python 文件处理 Python 读取文件 Python 写入/创建文件 Python 删除文件

Python 模块

NumPy 教程 Pandas 教程 SciPy 教程 Django 教程

Python Matplotlib

Matplotlib 简介 Matplotlib 入门 Matplotlib Pyplot Matplotlib 绘图 Matplotlib 标记 Matplotlib 线条 Matplotlib 标签 Matplotlib 网格 Matplotlib 子图 Matplotlib 散点图 Matplotlib 条形图 Matplotlib 直方图 Matplotlib 饼图

机器学习

入门 均值、中位数、众数 标准差 百分位数 数据分布 正态数据分布 散点图 线性回归 多项式回归 多元回归 尺度 训练/测试 决策树 混淆矩阵 层次聚类 逻辑回归 网格搜索 分类数据 K-means Bootstrap Aggregation 交叉验证 AUC - ROC 曲线 K-近邻

Python MySQL

MySQL 入门 MySQL 创建数据库 MySQL 创建表 MySQL 插入 MySQL 选择 MySQL Where MySQL Order By MySQL 删除 MySQL 删除表 MySQL 更新 MySQL Limit MySQL Join

Python MongoDB

MongoDB 入门 MongoDB 创建数据库 MongoDB 集合 MongoDB 插入 MongoDB Find MongoDB Query MongoDB Sort MongoDB 删除 MongoDB 删除集合 MongoDB 更新 MongoDB Limit

Python 参考

Python 概述 Python 内置函数 Python 字符串方法 Python 列表方法 Python 字典方法 Python 元组方法 Python 集合方法 Python 文件方法 Python 关键字 Python 异常 Python 词汇表

模块参考

Random 模块 Requests 模块 Statistics 模块 Math 模块 cMath 模块

Python 如何操作

删除列表重复项 反转字符串 两个数字相加

Python 示例

Python 示例 Python 编译器 Python 练习 Python 测验 Python 服务器 Python 面试问答 Python 训练营 Python 证书

Python Try Except


The try block lets you test a block of code for errors.

The except block lets you handle the error.

The else block lets you execute code when there is no error.

The finally block lets you execute code, regardless of the result of the try- and except blocks.


异常处理

When an error occurs, or exception as we call it, Python will normally stop and generate an error message.

These exceptions can be handled using the try statement

示例

The try block will generate an exception, because x is not defined

try
  print(x)
except
  print("An exception occurred")
自己动手试一试 »

Since the try block raises an error, the except block will be executed.

Without the try block, the program will crash and raise an error

示例

This statement will raise an error, because x is not defined

print(x)
自己动手试一试 »

多种异常

You can define as many exception blocks as you want, e.g. if you want to execute a special block of code for a special kind of error

示例

Print one message if the try block raises a NameError and another for other errors

try
  print(x)
except NameError
  print("Variable x is not defined")
except
  print("Something else went wrong")
自己动手试一试 »


Else

You can use the else keyword to define a block of code to be executed if no errors were raised

示例

In this example, the try block does not generate any error

try
  print("Hello")
except
  print("Something went wrong")
else
  print("Nothing went wrong")
自己动手试一试 »

Finally

The finally block, if specified, will be executed regardless if the try block raises an error or not.

示例

try
  print(x)
except
  print("Something went wrong")
finally
  print("The 'try except' is finished")
自己动手试一试 »

This can be useful to close objects and clean up resources

示例

Try to open and write to a file that is not writable

try
  f = open("demofile.txt")
  try
    f.write("Lorum Ipsum")
  except
    print("Something went wrong when writing to the file")
  finally
    f.close()
except
  print("Something went wrong when opening the file")
自己动手试一试 »

The program can continue, without leaving the file object open.


引发异常

As a Python developer you can choose to throw an exception if a condition occurs.

To throw (or raise) an exception, use the raise keyword.

示例

Raise an error and stop the program if x is lower than 0

x = -1

if x < 0
  raise Exception("Sorry, no numbers below zero")
自己动手试一试 »

The raise keyword is used to raise an exception.

You can define what kind of error to raise, and the text to print to the user.

示例

Raise a TypeError if x is not an integer

x = "hello"

if not type(x) is int
  raise TypeError("Only integers are allowed")
自己动手试一试 »


×

联系销售

如果您想将 W3Schools 服务用于教育机构、团队或企业,请发送电子邮件给我们
sales@w3schools.com

报告错误

如果您想报告错误,或想提出建议,请发送电子邮件给我们
help@w3schools.com

W3Schools 经过优化,旨在方便学习和培训。示例可能经过简化,以提高阅读和学习体验。教程、参考资料和示例会不断审查,以避免错误,但我们无法保证所有内容的完全正确性。使用 W3Schools 即表示您已阅读并接受我们的使用条款Cookie 和隐私政策

版权所有 1999-2024 Refsnes Data。保留所有权利。W3Schools 由 W3.CSS 提供支持