Python3 - 异常处理

Python3 - 异常处理 首页 / Python3入门教程 / Python3 - 异常处理

可以将异常定义为程序中的异常情况,导致程序流程中断。

每当发生异常时,程序都会停止执行,因此不会执行其他代码。因此,异常是无法处理Python脚本的运行时错误。异常是表示错误的Python对象

Python提供了一种处理异常的方法,以便可以在不中断的情况下执行代码。如果不处理该异常,则解释器不会执行该异常之后存在的所有代码。

常见异常

Python提供了许多内置的异常,但是在这里无涯教程描述了常见的标准异常。下面列出了可以从标准Python程序抛出的常见异常列表。

  1. ZeroDivisionError  -  将数字除以零时发生。
  2. NameError                 -  找不到名称时会发生。它可以是本地的也可以是全局的。
  3. IndentationError     -  如果给出的缩进不正确。
  4. IOError                        -  输入输出操作失败时发生。
  5. EOFError                     -  到达文件末尾但仍在执行操作时发生。

正如已经讨论的那样,异常是一种异常情况,会中断程序的执行。

假设有两个变量 a b ,它们接受用户的输入并执行这些值的除法。如果用户输入零作为分母怎么办?它将通过 ZeroDivision 异常中断程序的执行。

a = int(input("Enter a:"))  
b = int(input("Enter b:"))  
c = a/b
print("a/b = %d" %c)  
  
#other code:  
print("Hi I am other part of the program")

输出:

Enter a:10
Enter b:0
Traceback (most recent call last):
  File "exception-test.py", line 3, in <module>
    c = a/b;
ZeroDivisionError: division by zero

上面的程序在语法上是正确的,但由于输入异常而导致错误。这种编程可能不适合或不建议用于项目,因为这些项目需要不间断地执行。这就是为什么异常处理在处理这些意外异常方面起着至关重要的作用。可以通过以下方式处理这些异常。

try-expect语句

如果Python程序包含可能引发异常的可疑代码,则必须将该代码放在 try 块中。 try 块后面必须带有 except 语句,该语句包含一个代码块,如果try块中存在某些异常,则将执行该代码块。

Python Exception handling
try:  
    #block of code   
  
except Exception1:  
    #block of code  
  
except Exception2:  
    #block of code  
  
#other code  

考虑以下示例。

try:
    a = int(input("Enter a:"))  
    b = int(input("Enter b:"))  
    c = a/b
except:
    print("Can't divide with zero")

输出:

Enter a:10
Enter b:0
Can't divide with zero

还可以将else语句与try-except语句一起使用,如果没有异常发生在try块中,可以将要在场景中执行的代码放在其中。

下面给出了将else语句与try-except语句结合使用的语法。

try:  
    #block of code   
  
except Exception1:  
    #block of code   
  
else:  
    #this code executes if no except block is executed  
Python Exception handling

考虑下面的程序。

try:  
    a = int(input("Enter a:"))  
    b = int(input("Enter b:"))  
    c = a/b
    print("a/b = %d"%c)  
# Using Exception with except statement. If we print(Exception) it will return exception class
except Exception:  
    print("can't divide by zero")  
    print(Exception)
else:  
    print("Hi I am else block")   

输出:

Enter a:10
Enter b:0
can't divide by zero
<class 'Exception'>

try-except-else语句

Python提供了不使用异常语句指定异常名称的灵活性。

try:  
    a = int(input("Enter a:"))  
    b = int(input("Enter b:"))  
    c = a/b;  
    print("a/b = %d"%c)  
except:  
    print("can't divide by zero")  
else:  
    print("Hi I am else block")   

except语句

可以在 except 语句中使用异常变量。通过使用 as 关键字来使用它。该对象将返回异常原因。考虑以下示例:

try:  
    a = int(input("Enter a:"))  
    b = int(input("Enter b:"))  
    c = a/b
    print("a/b = %d"%c)  
    # Using exception object with the except statement
except Exception as e:  
    print("can't divide by zero")  
    print(e)
else:  
    print("Hi I am else block")   

输出:

Enter a:10
Enter b:0
can't divide by zero
division by zero

要记住的要点

  1. Python有助于不使用except语句指定异常。
  2. 可以在except语句中声明多个异常,因为try块可能包含引发不同类型异常的语句。
  3. 还可以指定一个else块以及try-except语句,如果try块中没有引发异常,则将执行该语句。
  4. 不引发异常的语句应放在else块中。
try:  
    #this will throw an exception if the file doesn't exist.   
    fileptr = open("file.txt","r")  
except IOError:  
    print("File not found")  
else:  
    print("The file opened successfully")  
    fileptr.close()  

输出:

File not found

声明多个异常

Python允许使用except子句声明多个异常。在try块引发多个异常的情况下,声明多个异常非常有用。语法如下。

try:  
    #block of code   
  
except (<Exception 1>,<Exception 2>,<Exception 3>,...<Exception n>)  
    #block of code   
  
else:  
    #block of code  

考虑以下示例。

try:    
    a=10/0;    
except(ArithmeticError, IOError):    
    print("Arithmetic Exception")    
else:    
    print("Successfully Done")     

输出:

Arithmetic Exception

try...finally语句

Python提供了可选的 finally 语句,该语句与 try 语句一起使用。无论发生什么异常,它都会被执行并用于释放外部资源。 finally块提供了执行保证。

可以将finally块与try块一起使用,在其中可以调整必要的代码,这些代码必须在try语句引发异常之前执行。

下面给出了使用finally块的语法。

try:  
    # block of code   
    # this may throw an exception  
finally:  
    # block of code  
    # this will always be executed   
Python Exception handling
try:  
    fileptr = open("file2.txt","r")    
    try:  
        fileptr.write("Hi I am good")  
    finally:  
        fileptr.close()  
        print("file closed")  
except:  
    print("Error")  

输出:

file closed
Error

raise异常

使用Python中的 raise 子句可以强制引发异常。在需要引发异常以停止程序执行的情况下,此方法很有用。

例如,有一个程序需要2GB的内存才能执行,如果该程序试图占用2GB的内存,则无涯教程可以引发异常以停止程序的执行。

下面给出了使用raise语句的语法。

raise Exception_class,<value>  

要记住的要点

  1. 要引发异常,请使用raise语句。异常类名紧随其后。
  2. 可以为异常提供一个可以在括号中给出的值。
  3. 使用值" as "的关键字。 " e "用作存储异常值的参考变量。
  4. 可以将值传递给异常以指定异常类型。
try:    
    age = int(input("Enter the age:"))    
    if(age<18):    
        raise ValueError   
    else:    
        print("the age is valid")    
except ValueError:    
    print("The age is not valid")    

输出:

Enter the age:17
The age is not valid

例 2 Raise the exception with message

try:  
     num = int(input("Enter a positive integer: "))  
     if(num <= 0):  
# we can pass the message in the raise statement  
         raise ValueError("That is  a negative number!")  
except ValueError as e:  
     print(e)  

输出:

Enter a positive integer: -5
That is a negative number!

例 3

try:  
    a = int(input("Enter a:"))  
    b = int(input("Enter b:"))  
    if b is 0:  
        raise ArithmeticError
    else:  
        print("a/b = ",a/b)  
except ArithmeticError:  
    print("The value of b can't be 0")

输出:

Enter a:10
Enter b:0
The value of b can't be 0

自定义异常

Python允许创建可以从程序中引发并使用except子句捕获的异常。但是,建议您在访问Python对象和类之后阅读本节。

考虑以下示例。

class ErrorInCode(Exception):    
    def __init__(self, data):    
        self.data = data    
    def __str__(self):    
        return repr(self.data)    
    
try:    
    raise ErrorInCode(2000)    
except ErrorInCode as ae:    
    print("Received error:", ae.data)    

输出:

Received error: 2000

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

软件测试52讲 -〔茹炳晟〕

如何设计一个秒杀系统 -〔许令波〕

算法面试通关40讲 -〔覃超〕

数据分析实战45讲 -〔陈旸〕

Serverless入门课 -〔蒲松洋(秦粤)〕

互联网人的英语私教课 -〔陈亦峰〕

Linux内核技术实战课 -〔邵亚方〕

手机摄影 -〔@随你们去〕

程序员的测试课 -〔郑晔〕

好记忆不如烂笔头。留下您的足迹吧 :)