python之异常

一、异常与错误

1、语法错误

错误一:
if

错误二:

def  text:
      pass

错误三:
 print(sjds

2、逻辑错误

#用户输入不完整(比如输入为空)或者输入非法(输入不是数字)

num=input('>>:')
     int(num)

#无法计算
rest=1/0
rest2=1+str

什么是异常:

            程序运行时发生错误的信号

异常种类:

         在python中不同的异常可以用不同的类型去标识,不同的类对象标识不同的异常,一个异常标识一种错误

l=['egon','aa']
l[3]
触发IndentationError
dic={'name':'egon'}
dic['age']
触发KeyError
s='hello'
int(s)
触发ValueError
AttributeError 试图访问一个对象没有的树形,比如foo.x,但是foo没有属性x
IOError 输入/输出异常;基本上是无法打开文件
ImportError 无法引入模块或包;基本上是路径问题或名称错误
IndentationError 语法错误(的子类) ;代码没有正确对齐
IndexError 下标索引超出序列边界,比如当x只有三个元素,却试图访问x[5]
KeyError 试图访问字典里不存在的键
KeyboardInterrupt Ctrl+C被按下
NameError 使用一个还未被赋予对象的变量
SyntaxError Python代码非法,代码不能编译(个人认为这是语法错误,写错了)
TypeError 传入对象类型与要求的不符合
UnboundLocalError 试图访问一个还未被设置的局部变量,基本上是由于另有一个同名的全局变量,
导致你以为正在访问它
ValueError 传入一个调用者不期望的值,即使值的类型是正确的
常用的异常
什么时候用异常处理:你能想到有异常,并且可能出现在这一块代码的异常有很多种,不能一一枚举
禁止在大段代码外面套异常处理
try:
    pass
except ValueError:
    pass
except Exception as e:
    print('统筹处理所有错误的措施')
else:
    print("针对这段try中的代码没有异常要特别处理的")
finally:
    print("不管有没有异常都要执行的代码")
View Code

异常处理:

  首先须知,异常是由程序的错误引起的,语法上的错误跟异常处理无关,必须在程序运行前就修正

复制代码
#_*_coding:utf-8_*_
__author__ = 'Linhaifeng'

num1=input('>>: ') #输入一个字符串试试
if num1.isdigit():
    int(num1) #我们的正统程序放到了这里,其余的都属于异常处理范畴
elif num1.isspace():
    print('输入的是空格,就执行我这里的逻辑')
elif len(num1) == 0:
    print('输入的是空,就执行我这里的逻辑')
else:
    print('其他情情况,执行我这里的逻辑')

'''
问题一:
使用if的方式我们只为第一段代码加上了异常处理,但这些if,跟你的代码逻辑并无关系,这样你的代码会因为可读性差而不容易被看懂

问题二:
这只是我们代码中的一个小逻辑,如果类似的逻辑多,那么每一次都需要判断这些内容,就会倒置我们的代码特别冗长。
'''
复制代码
使用if判断进行异常处理

python为每一种异常定制了一个类型,然后提供了一种特定的语法结构用来进行异常处理

f = open('a.txt')

g = (line.strip() for line in f)
for line in g:
    print(line)
else:
    f.close()
复制代码
读文件例1
复制代码
try:
    f = open('a.txt')
    g = (line.strip() for line in f)
    print(next(g))
    print(next(g))
    print(next(g))
    print(next(g))
    print(next(g))
except StopIteration:
    f.close()

'''
next(g)会触发迭代f,依次next(g)就可以读取文件的一行行内容,无论文件a.txt有多大,同一时刻内存中只有一行内容。
提示:g是基于文件句柄f而存在的,因而只能在next(g)抛出异常StopIteration后才可以执行f.close()
'''
读文件例2
class EvaException(BaseException):
    def __init__(self,msg):
        self.msg=msg
    def __str__(self):
        return self.msg

try:
    raise EvaException('类型错误')
except EvaException as e:
    print(e)
自定义异常
try:
    raise TypeError('类型错误')
except Exception as e:
    print(e)
自动触发异常

常用模块

摘要算法,不是一个解密算法
检测一个字符串是否发生了变化
 hashlib
import hashlib
md5_obj = hashlib.md5('nezha'.encode('utf-8'))
md5_obj.update('123456'.encode('utf-8'))
print(md5_obj.hexdigest())
md5_obj.update('hello,egon~'.encode('utf-8'))
print(md5_obj.hexdigest())

文件校验
文件是否被改变
登录密码
不能解密,但可以“撞库”
加盐 hashlib.md5('nezha'.encode('utf-8'))
user = 'alex'
pwd = '3713'
md5_obj = hashlib.md5(user.encode('utf-8'))
md5_obj.update(pwd.encode('utf-8'))
print(md5_obj.hexdigest())

import hashlib
md5_obj = hashlib.md5()
import os
filesize = os.path.getsize('filename')
f = open('filename','rb')
while filesize>0:
    if filesize > 1024:
        content = f.read(1024)
        filesize -= 1024
    else:
        content = f.read(filesize)
        filesize -= filesize
    md5_obj.update(content)
# for line in f:
#     md5_obj.update(line.encode('utf-8'))
md5_obj.hexdigest()
View Code
configparser模块
import configparser

config = configparser.ConfigParser()

config["DEFAULT"] = {'ServerAliveInterval': '45',
                      'Compression': 'yes',
                     'CompressionLevel': '9',
                     'ForwardX11':'yes'
                     }

config['bitbucket.org'] = {'User':'hg'}

config['topsecret.server.com'] = {'Host Port':'50022','ForwardX11':'no'}

with open('example.ini', 'w') as configfile:

   config.write(configfile)
import configparser

config = configparser.ConfigParser()

#---------------------------查找文件内容,基于字典的形式

print(config.sections())        #  []

config.read('example.ini')

print(config.sections())        #   ['bitbucket.org', 'topsecret.server.com']

print('bytebong.com' in config) # False
print('bitbucket.org' in config) # True


print(config['bitbucket.org']["user"])  # hg

print(config['DEFAULT']['Compression']) #yes

print(config['topsecret.server.com']['ForwardX11'])  #no


print(config['bitbucket.org'])          #<Section: bitbucket.org>

for key in config['bitbucket.org']:     # 注意,有default会默认default的键
    print(key)

print(config.options('bitbucket.org'))  # 同for循环,找到'bitbucket.org'下所有键

print(config.items('bitbucket.org'))    #找到'bitbucket.org'下所有键值对

print(config.get('bitbucket.org','compression')) # yes       get方法Section下的key对应的value
查找文件
 
 
 
 


原文地址:https://www.cnblogs.com/mengqingjian/p/7383857.html