Python学习笔记

xiaoxiao2021-03-01  4

10.3 异常

Python 程序的异常处理 , Python使用时被称为异常的特殊对象来管理程序执行期间发生的错误.每当发生让Python不知所措的错误时,他都会创建一个异常对象.如果编写了处理该异常的代码,程序会继续运行;如果未对异常进行处理,程序将停止,并显示一个traceback .

  在python中是使用try-except代码块处理的.try-except代码块让Python执行指定的操作,同时告诉python发生异常时怎么办.使用了try-except代码块处理,即使程序出现异常,程序也会继续运行.

10.3.1 处理 ZeroDivisionError 异常

print(5/0) 异常 : Traceback (most recent call last): File "D:/Pythonfile/pan.py", line 61, in <module> print(5/0) ZeroDivisionError: division by zero

10.3.2  使用 try -except 代码块

try: print(5/0) except ZeroDivisionError: print("You can't divide by zero !")

我们将导致错误的代码行print(5/0)  放在一个try代码块中.如果try 代码块中的代码运行起来没有问题,Python将跳过except代码段,

;如果try代码块中有异常,Python将查找这样的except代码块,并运行其中的代码,即其中指定的错误与引发的错误相同.

      在这个示例中,try代码块中的代码引发了ZeroDivisionError 异常 ,因此Python指出了该如何解决问题的except代码块,并运行其中的代码.

10.3.3 使用异常避免崩溃

     发生错误时,如果程序还有工作没有完成,妥善的处理错误就尤为重要.

print("Give me two numbers ,and I 'll divide them ") print("Enter 'q' to quit ") while True : first_number = input("\nfirst number .") if first_number == 'q': break second_number = input("\nsecond number .") if second_number == 'q': break try: answer = int(first_number) / int(second_number) except ZeroDivisionError: print("You can't divide zero ") else: print(answer)

我们在这里做了一个异常处理,当出现分母为0时,程序会抛出异常,try-except 会避免程序崩溃 .当没有异常时执行else语句 .

 

10.3.5 处理 FileNotFoundError

       在我们使用文件操作时,常见的问题比如,我要打开一个文件,但是在输入文件名的时候,文件名不正确,或者压根就没有这个文件,对于这样的情景我们就要使用 try -excpt 处理

filename = 'alice.txt' with open(filename) as file_object: contents = file_object.read() 异常 : Traceback (most recent call last): File "D:/Pythonfile/pan.py", line 62, in <module> with open(filename) as file_object: FileNotFoundError: [Errno 2] No such file or directory: 'alice.txt'

处理之后

filename = 'alice.txt' try: with open(filename) as file_object: contents = file_object.read() except FileNotFoundError: msg = "Sorry ,the file "+filename +"does not exist " print(msg) Sorry ,the file alice.txtdoes not exist

10.3.6  分析文本

计算 hamlet 文本中的单词数量

filename = 'hamlet.txt' try: with open(filename,'r') as file_object: contents = file_object.read() except FileNotFoundError: msg = "Sorry ,the file "+filename +"does not exist " else: words = contents.split() # 将字符串创建列表 num_words = len(words) print("The file "+filename + "has about "+str(num_words)+" words .") Output: The file hamlet.txthas about 32013 words . def count_words(filename): """ 计算一份文件中大致包含多少个单词""" try: with open(filename) as file_object: contents = file_object.read() except FileNotFoundError: msg = "Sorry ,the file " + filename + "does not exist " else: words = contents.split() num_words = len(words) print("The file " + filename + "has about " + str(num_words) + " words .") ls = ['1.txt','2.txt','3.txt'] for filename in ls: count_words(filename)

未完....

 

转载请注明原文地址: https://www.6miu.com/read-3200329.html

最新回复(0)