python之try except的使用

1.try-except常用语法:

try仅有一块,但是except可以有多个

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

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

  • (Error1, Error2,…) 、(Error3, Error4,…):其中,Error1、Error2、Error3 和 Error4 都是具体的异常类型。显然,一个 except 块可以同时处理多种异常。
  • [as e]:作为可选参数,表示给异常类型起一个别名 e,这样做的好处是方便在 except 块中调用异常类型(后续会用到)。
  • [Exception]:作为可选参数,可以代指程序可能发生的所有异常情况,其通常用在最后一个 except 块。

python解释器会根据发生的异常,根据对应的异常类型来选择对应的except块来处理 

2. try-except处理流程:

1,捕获异常

当处理try模块发生异常时,系统会自动生成一个异常类型,并且将该异常发提交给解释器。

2,处理异常

当解释器收到异常对象时,会寻找能处理该异常的except块。找到合适的就将该异常对象交给该except块处理。如果没有合适的except块则,则程序运行终止,python解释器也退出。

事实上,不管程序代码块是否处于 try 块中,甚至包括 except 块中的代码,只要执行该代码块时出现了异常,系统都会自动生成对应类型的异常。但是,如果此段程序没有用 try 包裹,又或者没有为该异常配置处理它的 except 块,则 Python 解释器将无法处理,程序就会停止运行;反之,如果程序发生的异常经 try 捕获并由 except 处理完成,则程序可以继续执行。

例如:

import requests
w_url="http://baiduddd.com"

def test_try_except():
    try:
        print("开始请求地址")
        wiki_res = requests.get(w_url)
        if wiki_res.status_code == 200:
            login_suc=True
        else:
            login_suc = False
    except Exception as e:
        print("发生异常。。。。e:",e)
        login_suc=False
    print("继续运行。。。。")

test_try_except()

结果:
开始请求地址
发生异常。。。。e: HTTPConnectionPool(host='baiduddd.com', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x000001AFD501F340>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))
继续运行。。。。

有些requests请求的访问异常不是通过判断响应的status_code就能知道的,若是那些导致请求都无法建立的情况下,requests不使用try-except的话会直接500导致程序中止。使用try-except的话会捕获发生的异常,继续执行下去或者正常报告异常。

3.try-except-else-finally处理流程

else 模块将在 try模块没有发生任何异常的时候执行

finally模块是不管异常有无发生,最后都会执行到的代码

try:
    print("try模块")
except Exception as error:
    print(error)
else:
    print("else模块")
finally:
    print("finally模块")

结果:

try模块
else模块
finally模块

若try模块正常执行并且有return返回,finally模块存在的话,会在return前去执行finally模块

def try_test():
    try:
        res=0
        return res
    except Exception as e:
        print(repr(e))
    finally:
        print("finally")
res=try_test()
print("res=",res)

打印结果:

——————————-
finally
res= 0 

 4.用户抛出异常

raise抛出异常

x=11
if x>10:
    raise Exception("x不能大于10")

结果:

Traceback (most recent call last):
  File "C:/项目/python_tool/python_other_test/tryexcept.py", line 33, in <module>
    raise Exception("x不能大于10")
Exception: x不能大于10

5.用户自定义异常

用户可自定义异常,但是需要继承自Exception类

class MyError(Exception):
        # 直接继承或者间接继承均可
        def __init__(self, value):
            self.value = value
        def __str__(self):
            return repr(self.value)
x=11
if x>10:
    raise MyError("x不能大于10")

结果:

Traceback (most recent call last):
  File "C:/项目/python_tool/python_other_test/tryexcept.py", line 39, in <module>
    raise MyError("x不能大于10")
__main__.MyError: 'x不能大于10'

6.异常类型常用属性及方法

e.args:异常的错误编号及描述字符串

str(e):异常的错误信息

repr(e):较全面的异常信息

import requests
w_url="http://baiduddd.com"

def test_try_except():
    try:
        print("开始请求地址")
        wiki_res = requests.get(w_url)
        if wiki_res.status_code == 200:
            login_suc=True
        else:
            login_suc = False
    except Exception as e:
        print("异常的错误编号及描述字符串:",e.args)
        print("异常的错误信息:",str(e))
        print("异常信息,较全面的异常信息:",repr(e))
        login_suc=False
    print("继续运行。。。。")

test_try_except()

结果:

开始请求地址
异常的错误编号及描述字符串: (MaxRetryError("HTTPConnectionPool(host='baiduddd.com', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x0000014D5CC8F340>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))"),)
异常的错误信息: HTTPConnectionPool(host='baiduddd.com', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x0000014D5CC8F340>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))
异常信息,较全面的异常信息: ConnectionError(MaxRetryError("HTTPConnectionPool(host='baiduddd.com', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x0000014D5CC8F340>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))"))
继续运行。。。。

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
乘风的头像乘风管理团队
上一篇 2023年10月17日
下一篇 2023年10月17日

相关推荐

此站出售,如需请站内私信或者邮箱!