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

WBOY
Release: 2023-05-22 23:37:17
forward
1875 people have browsed it

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!

Related labels:
source:yisu.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
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