可以将异常定义为程序中的异常情况,导致程序流程中断。
每当发生异常时,程序都会停止执行,因此不会执行其他代码。因此,异常是无法处理Python脚本的运行时错误。异常是表示错误的Python对象
Python提供了一种处理异常的方法,以便可以在不中断的情况下执行代码。如果不处理该异常,则解释器不会执行该异常之后存在的所有代码。
Python提供了许多内置的异常,但是在这里无涯教程描述了常见的标准异常。下面列出了可以从标准Python程序抛出的常见异常列表。
正如已经讨论的那样,异常是一种异常情况,会中断程序的执行。
假设有两个变量 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
上面的程序在语法上是正确的,但由于输入异常而导致错误。这种编程可能不适合或不建议用于项目,因为这些项目需要不间断地执行。这就是为什么异常处理在处理这些意外异常方面起着至关重要的作用。可以通过以下方式处理这些异常。
如果Python程序包含可能引发异常的可疑代码,则必须将该代码放在 try 块中。 try 块后面必须带有 except 语句,该语句包含一个代码块,如果try块中存在某些异常,则将执行该代码块。
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
考虑下面的程序。
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'>
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 语句中使用异常变量。通过使用 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
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
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
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
使用Python中的 raise 子句可以强制引发异常。在需要引发异常以停止程序执行的情况下,此方法很有用。
例如,有一个程序需要2GB的内存才能执行,如果该程序试图占用2GB的内存,则无涯教程可以引发异常以停止程序的执行。
链接:https://www.learnfk.comhttps://www.learnfk.com/python3/python-exception-handling.html
来源:LearnFk无涯教程网
下面给出了使用raise语句的语法。
raise Exception_class,<value>
要记住的要点
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
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)