在python中什么是异常?在程序中为什么抛异常?抛异常的几种方式

版权声明:本文为博主原创文章,未经博主允许不得转载 https://blog.csdn.net/g_optimistic/article/details/89576470

目录

1.什么是异常?

2.在程序中为什么抛异常?

3.抛异常的几种方式

4.异常的好处

5.爬虫过程中经常出现的异常


1.什么是异常?

异常就是程序执行过程中发生的错误

异常即是一个事件,该事件会在程序执行过程中发生,影响了程序的正常执行。

一般情况下,在Python无法正常处理程序时就会发生一个异常。

异常是Python对象,表示一个错误。

当Python脚本发生异常时我们需要捕获处理它,否则程序会终止执行。

扫描二维码关注公众号,回复: 6069500 查看本文章

2.在程序中为什么抛异常?

抛异常是为了让当次执行的程序中断

如果不抛异常,整个程序就会全部终止

3.抛异常的几种方式

(1)使用·except而不带任何异常类型

try:
    正常的操作;
    ....
except:
    发生异常,执行这块代码
    .....
else:
    如果没有异常执行这块代码

(2)使用except而带多种异常类型

try:
    正常的操作
    ....
except(Exception1[, Exception2[,...ExceptionN]]]):
    发生以上异常中的一个,执行这块代码
    .....
else:
    如果没有异常执行这块代码

(3)try-finally

无论是否发生异常都会执行最后的代码

try:
    语句
finally:
    语句   # 退出try时总会执行
raise

(4)用户自定义异常   raise

try:
    raise NetworkError('Bad hostname')
except NetworkError as e:
    print(e)

4.异常的好处

(1)保证程序的健壮性     代码经得起各种情况的摧残

(2)对于有问题的数据进行收集,做好留痕工作

import requests
from requests.exceptions import ConnectionError
url_list=[
    'http://www.langlang2017.com',
    'http://xxx.com/0000000.html',
    'http://www.baidu.com'
]
for url in url_list:
    try:
        response=requests.get(url)
        print('------------:',url)
    except ConnectionError:
        with open('except_list.txt','a',encoding='utf=8') as fp:
            fp.write(url)

5.爬虫过程中经常出现的异常

requests中存在的异常在:requests.exceptions

(1)requests.exceptions.ConnectionError   未知服务器

(2)requests.exceptions.ConnectTimeout  连接\读取超时

(3)requests.exceptions.ProxyError  代理服务器异常   代理连接不上

import requests
from requests.exceptions import ConnectionError
url_list=[
    'htttp://www.langlang2017.com',
    'http://www.xxx.com/000000000.html',
    'http://www.baidu.com',
]
for url in url_list:
    try:
        response=requests.get(url)
        print('--------:',url)
    except ConnectionError as e:
        print(url,'有问题')
        print('ConnectionError:\n',e)
    except Exception as e:
        print(e)

猜你喜欢

转载自blog.csdn.net/g_optimistic/article/details/89576470
今日推荐