Table of Contents
1 | Syntax error
2 | Run-time error
3 |Other exceptions
4 | 异常处理
try except 语句的执行流程如下:
5 | 获取特定异常的有关信息
6 |finally语句
Home Backend Development Python Tutorial What are the methods for catching and handling exceptions in Python

What are the methods for catching and handling exceptions in Python

May 22, 2023 pm 11:37 PM
python

1 | Syntax error

refers to errors that occur when parsing the code. When the code does not comply with Python syntax rules, the Python interpreter will report a SyntaxError syntax error during parsing, and at the same time, it will clearly point out the earliest statement where the error was detected. For example:

print "Hello,World!"
Copy after login

We know that Python 3.0 no longer supports the above writing method, so at run time, the interpreter will report the following error:

SyntaxError: Missing parentheses in call to 'print'
Copy after login

Syntax error Most of them are caused by the developer's negligence. They are real errors and cannot be tolerated by the interpreter. Therefore, the program can only be executed if all grammatical errors in the program are corrected.

2 | Run-time error

Run-time error means that the program is syntactically correct, but an error occurs during runtime. For example:

a = 1/0
Copy after login

The above code means "divide 1 by 0 and assign it to a. Because 0 is meaningless as a divisor, the following error will occur after running:

Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> 1/0 ZeroDivisionError: division by zero
Copy after login

3 |Other exceptions

In the above running output results, the first two paragraphs indicate the location of the error, and the last sentence indicates the type of error. In Python, This kind of error situation during runtime is called Exceptions.

There are many such exceptions. The common exceptions are as follows:

AttributeErrorException thrown when the object attribute attempted to be accessed does not existIndexErrorThe index exceeds the range of the sequence and this exception will be thrownKeyErrorSearch in dictionary This exception is thrown when a keyword does not existNameErrorThis exception is thrown when trying to access an undeclared variable##TypeError>>> 1 "2"ZeroDivisionError>>> a = 1 /0

4 | 异常处理

程序运行时出现异常,目的并不是让我们的程序直接终止!Python是希望在出现异常时,我们可以编写代码来对异常进行处理!

Python 提供了try except语句捕获并处理异常,该异常处理语句的基本语法结构如下:

try:
    # 可能产生异常的代码块
except [(Error1, Error2, ...) [as e]]:
    # 处理异常的代码块1
except [(Error3, Error4, ...) [as e]]:
    # 处理异常的代码块2
Copy after login

该格式中,[ ] 括起来的部分可以使用,也可以省略。其中各部分的含义如下:

  • (Error1, Error2,...) 、(Error3, Error4,...):其中,Error1、Error2、Error3 和Error4 都是具体的异常类型。显然,一个 except 块可以同时处理多种异常。

  • [as e]:作为可选参数,表示给异常类型起一个别名 e,这样做的好处是方便在except 块中调用异常类型(后续会用到)。

  • [Exception]:作为可选参数,可以代指程序可能发生的所有异常情况,其通常用在最后一个 except 块。

  • 注:except 后面也可以不指定具体的异常名称,这样的话,表示要捕获所有类型的异常。

另外,从 try except 的基本语法格式可以看出,try 代码块仅有一个,但except 代码块可以有多个,这是为了针对不同的异常类型提供不同的异常处理方式。当程序发生不同的意外情况时,会对应不同的异常类型,Python 解释器就会根据该异常类型来决定使用哪个 except 块来处理该异常。

try except 语句的执行流程如下:

1、首先执行 try 中的代码块,如果执行过程中出现异常,系统会自动生成一个异常类型,并将该异常提交给 Python 解释器,此过程称为捕获异常。

2、当 Python 解释器收到异常对象时,会寻找能处理该异常对象的 except 块,如果找到合适的 except 块,则把该异常对象交给该 except 块处理,这个过程被称为处理异常。如果 Python 解释器找不到处理异常的 except 块,则程序运行终止,Python 解释器也将退出。

异常处理例子:

try:
    a = int(input("输入被除数:"))
    b = int(input("输入除数:"))
    c = a / b
    print("您输入的两个数相除的结果是:", c )
except (ValueError, ArithmeticError):
    print("程序发生了数字格式异常、算术异常之一")
except :
    print("未知异常")
print("程序继续运行")
Copy after login

程序运行结果为:

输入被除数:a程序发生了数字格式异常,算术异常之一程序继续运行
Copy after login

上面程序中,第 6 行代码使用了(ValueError, ArithmeticError)来指定所捕获的异常类型,这就表明该 except 块可以同时捕获这 2 种类型的异常;第 8 行代码只有 except 关键字,并未指定具体要捕获的异常类型,这种省略异常类的 except 语句也是合法的,它表示可捕获所有类型的异常,一般会作为异常捕获的最后一个 except 块。除此之外,由于 try 块中引发了异常,并被 except 块成功捕获,因此程序才可以继续执行,才有了“程序继续运行”的输出结果。

通过在try块后提供多个except块可以无须在异常处理块中使用if判断异常类型,但依然可以针对不同的异常类型提供相应的处理逻辑,从而提供更细致、更有条理的异常处理逻辑。

事实上,不管程序代码块是否处于 try 块中,甚至包括 except 块中的代码,只要执行该代码块时出现了异常,系统总会自动生成一个 Error 对象。如果程序没有为这段代码定义任何的 except 块,则 Python 解释器无法找到处理该异常的 except 块,程序就会停止运行;反之,如果程序发生异常,并且该异常经 try 捕获并由 except 处理完成,则程序会继续执行。

5 | 获取特定异常的有关信息

每种异常类型都提供了如下几个属性和方法,通过调用它们,就可以获取当前处理异常类型的相关信息:

  • args:返回异常的错误编号和描述字符串;

  • str(e):返回异常信息,但不包括异常信息的类型;

  • repr(e):返回较全的异常信息,包括异常信息的类型。

try:
    result=20/int(input("请输入除数:"))
    print(result)
except ValueError:
  print("必须输入整数")
except ArithmeticError:
  print("算数错误,除数不能为 0")
else:
    print("没有出现异常")
print("继续运行")
Copy after login

程序运行结果为:

输入被除数:210没有出现异常继续运行
Copy after login

6 |finally语句

Python 异常处理机制还提供了一个 finally 语句,用来为 try 块中的程序做扫尾清理工作。

在整个异常处理机制中,finally 语句的功能是:无论 try 块是否发生异常,最终都要进入 finally 语句,并执行其中的代码块。

finally 示例:

try:
    a=20/int(input("请输入 a 的值:"))
    print(a)
except:
  print("发生异常")
else:
  print("执行 else 代码块")
finally:
    print("执行 finally 代码块")
Copy after login

finally 代码块的强大还远不止此,即便当 try 块发生异常,且没有合适和except 处理异常时,finally 块中的代码也会得到执行。

The above is the detailed content of What are the methods for catching and handling exceptions in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Do mysql need to pay Do mysql need to pay Apr 08, 2025 pm 05:36 PM

MySQL has a free community version and a paid enterprise version. The community version can be used and modified for free, but the support is limited and is suitable for applications with low stability requirements and strong technical capabilities. The Enterprise Edition provides comprehensive commercial support for applications that require a stable, reliable, high-performance database and willing to pay for support. Factors considered when choosing a version include application criticality, budgeting, and technical skills. There is no perfect option, only the most suitable option, and you need to choose carefully according to the specific situation.

HadiDB: A lightweight, horizontally scalable database in Python HadiDB: A lightweight, horizontally scalable database in Python Apr 08, 2025 pm 06:12 PM

HadiDB: A lightweight, high-level scalable Python database HadiDB (hadidb) is a lightweight database written in Python, with a high level of scalability. Install HadiDB using pip installation: pipinstallhadidb User Management Create user: createuser() method to create a new user. The authentication() method authenticates the user's identity. fromhadidb.operationimportuseruser_obj=user("admin","admin")user_obj.

Navicat's method to view MongoDB database password Navicat's method to view MongoDB database password Apr 08, 2025 pm 09:39 PM

It is impossible to view MongoDB password directly through Navicat because it is stored as hash values. How to retrieve lost passwords: 1. Reset passwords; 2. Check configuration files (may contain hash values); 3. Check codes (may hardcode passwords).

How to optimize MySQL performance for high-load applications? How to optimize MySQL performance for high-load applications? Apr 08, 2025 pm 06:03 PM

MySQL database performance optimization guide In resource-intensive applications, MySQL database plays a crucial role and is responsible for managing massive transactions. However, as the scale of application expands, database performance bottlenecks often become a constraint. This article will explore a series of effective MySQL performance optimization strategies to ensure that your application remains efficient and responsive under high loads. We will combine actual cases to explain in-depth key technologies such as indexing, query optimization, database design and caching. 1. Database architecture design and optimized database architecture is the cornerstone of MySQL performance optimization. Here are some core principles: Selecting the right data type and selecting the smallest data type that meets the needs can not only save storage space, but also improve data processing speed.

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How to use AWS Glue crawler with Amazon Athena How to use AWS Glue crawler with Amazon Athena Apr 09, 2025 pm 03:09 PM

As a data professional, you need to process large amounts of data from various sources. This can pose challenges to data management and analysis. Fortunately, two AWS services can help: AWS Glue and Amazon Athena.

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Can mysql connect to the sql server Can mysql connect to the sql server Apr 08, 2025 pm 05:54 PM

No, MySQL cannot connect directly to SQL Server. But you can use the following methods to implement data interaction: Use middleware: Export data from MySQL to intermediate format, and then import it to SQL Server through middleware. Using Database Linker: Business tools provide a more friendly interface and advanced features, essentially still implemented through middleware.

See all articles
Exception typeMeaningInstance
AssertionErrorWhen assert keyword When the condition is false, the program will stop and throw this exception##>>> assert 1>0

>>> assert 1<0

AssertionError

>>> s="hello"

>>> s.len

AttributeError: 'str' object has no attribute'len'

>>> s="hello"

>>> s[5]

IndexError: string index out of range

>>> demo_dict={"age": 20}

>>> demo_dict[" name"]

KeyError: 'name'

>>> hello

NameError: name 'hello' is not defined

Invalid operations between different types of data

TypeError: unsupported operand type(s) for : 'int' and 'str '

The divisor in the division operation is 0. This exception is raised

ZeroDivisionError: division by zero