异常处理

为什么要用异常处理?

  写代码出现报错的的情况,首先检查逻辑是不是有问题,在逻辑没问题还会报错的情况下,找到具体报错的那一行代码,在这行代码上加上try,再根据错误类型进行处理.

什么情况下需要进行异常处理?

在我们程序写定的时候无法预料的错误和异常,就需要在代码中处理

首先我们要杜绝一些常规的错误,但是是不可能滴...你总会错的

name                # NameError    

class A:pass
     A= error       # AttributeError 属性错误
    
                    # 所有的缩进错误,语法错误, 尽量在写代码的时候进行避免
  这几种报错尽量少出现!                          

1.常见的异常类型

int('abc')  ValueError
iterator = iter([1,2])   #iter 迭代器 ,括号里面放可迭代的参数
for i in iterator:   #  通过for循环 取值
    print(i)       #取得1,2
print(next(iterator))  #但是再通过next方法取值已经没了  就会出现 StopIteration 异常
iterator.__next__()

2.异常的结构和语法

单分支-1

try:
有可能出错的代码
except 错误类型1:
try:
    iterator = iter([])
    iterator.__next__()
except StopIteration:
    print('这样就不会报错了,还可以正常取到值')

 

单分支-2

try:

  有可能出错的代码

except (错误类型1,错误类型2,...):

l = ['生活','压力','__eq__','责任']
try:
    meusr = int(input('请输出序号显示l内容: '))
    print(l[meusr-1])
except (ValueError,IndexError): #同时处理掉值错误和超出l索引异常的情况
    print('请输入1个数字')

 

多分支-1

 

try:
有可能出错的代码
except 错误类型1:
处理这个错误
except 错误类型2:

l = ['生活','压力','__eq__','责任']
try:
    meusr = int(input('请输出序号显示l内容: ')) #可以看出输入除了数字的值或超过l索引值就会报错
    print(l[meusr-1])
except ValueError: #首先处理掉值错误的情况
    print('请输入1个数字')
except IndexError: #处理超出l范围的情况
    print('输入的数字无效')

as语句的应用

使用 as 语句得到一个错误信息的变量,使用这个变量,就可以知道错误的具体信息,在一定程度上方便了我们代码测试
l = ['生活','压力','__eq__','责任']
try:
    meusr = int(input('请输出序号显示l内容: '))
    print(l[meusr-1])
except (ValueError,IndexError) as err:  #当然 as 得到这个变量可以为任意
    print(type(err),err)
meusr = 6  就会输出<class 'IndexError'> list index out of range
meusr = a   就会输出<class 'ValueError'> invalid literal for int() with base 10: 'a'

万能异常(Exception)

和其他异常配合使用的时候,默认放在最后,尽量不要滥用万能异常

程序开发完后,在最外层添加异常处理,保证程序运行不会出现意外

try:

 可能出错的代码

expect:Exception as e: 

示例1

def func():
    so
def main():
    func()
try:
    main()
except Exception as e:
    print('出错了..',e)

示例2

l = ['生活','压力','__eq__','责任']
try:
    meusr = int(input('请输出序号显示l内容: '))
    print(l[meusr-1])
    name
except (ValueError,IndexError) as err:
    print(type(err),err)
except Exception as err:
    print(type(err),err)
#程序首先走ValueError,IndexError 进行比对,有异常处理,并输出异常类型 如果没有走万能异常并输出异常类型

注意:所有的异常处理都应该用最基础的最贴近的异常类型去处理它,而不是滥用万能异常

else结构  

 try:
有可能出错的代码
except (错误类型1,错误类型2,...):
处理这个错误
else:
不发生异常要做的操作
try:
     name
except Exception as e:
    print(e)   #输出 name 'name' is not defined
else:
    print('-------')  #并没有执行打印

finally

无论如何都会执行,关闭文件\归还系统资源(网上的连接\数据库的连接,遇到return \遇到程序报错结束,都会执行finally,再return或者报错停止运行!

def func():
    try:
        f = open('file','w')
        ret = f.read()  #写的模式下无法读
        return ret
        # f.close()  #上面代码报错后直接执行except,所以写到 finally方法中
    except Exception:
        print('报错了---')  # 处理异常后执行
    finally:  # 无论有没有异常都会执行
        f.close()  #鉴于文件打开后并没有关闭,执行finally
        print('closed---')
func()

raise抛出异常

普通示例1

try:
    f = open('file','r')
    ret = f.read()
finally:
    f.close()
    print('closed---')
raise ImportError

抽象类示例

在框架和规范中,提示按照规则写代码,加入主动抛出异常,提示规范编程

class A:
    def func(self):
        raise NotImplementedError   # 抛出异常,就是提示对象b只找自己类中的func,不再走父类中的func

class B(A):
    def func(self):
        print('B的func')

b = B()
b.func()
View Code

自定义异常,也就是自己写报错

class Nocoursre(BaseException):
    def __init__(self,msg):
        self.msg = msg
    def __str__(self):
        return self.msg
err = Nocoursre('没有这个课程')
print(err)
raise Nocoursre('没有这个课程')

class Nocourse(BaseException):
    def __str__(self):
        return '没有这个课程'
raise Nocourse()   #主动报异常
输出
__main__.NoCourse: 没有这个课程

断言

assert  必须满足的条件返回bool值,  否则返回False 报错,如果是True就执行

assert  1 == 1   #True就执行
print('继续执行')

 

 









 

 

 

 

 

 

 

 

 

 

 

 

...





 

posted @ 2018-11-29 14:54  FindSoul  阅读(220)  评论(0)    收藏  举报
var RENDERER = { POINT_INTERVAL : 5, FISH_COUNT : 3, MAX_INTERVAL_COUNT : 50, INIT_HEIGHT_RATE : 0.5, THRESHOLD : 50, init : function(){ this.setParameters(); this.reconstructMethods(); this.setup(); this.bindEvent(); this.render(); }, setParameters : function(){ this.$window = $(window); this.$container = $('#jsi-flying-fish-container'); this.$canvas = $(''); this.context = this.$canvas.appendTo(this.$container).get(0).getContext('2d'); this.points = []; this.fishes = []; this.watchIds = []; }, createSurfacePoints : function(){ var count = Math.round(this.width / this.POINT_INTERVAL); this.pointInterval = this.width / (count - 1); this.points.push(new SURFACE_POINT(this, 0)); for(var i = 1; i < count; i++){ var point = new SURFACE_POINT(this, i * this.pointInterval), previous = this.points[i - 1]; point.setPreviousPoint(previous); previous.setNextPoint(point); this.points.push(point); } }, reconstructMethods : function(){ this.watchWindowSize = this.watchWindowSize.bind(this); this.jdugeToStopResize = this.jdugeToStopResize.bind(this); this.startEpicenter = this.startEpicenter.bind(this); this.moveEpicenter = this.moveEpicenter.bind(this); this.reverseVertical = this.reverseVertical.bind(this); this.render = this.render.bind(this); }, setup : function(){ this.points.length = 0; this.fishes.length = 0; this.watchIds.length = 0; this.intervalCount = this.MAX_INTERVAL_COUNT; this.width = this.$container.width(); this.height = this.$container.height(); this.fishCount = this.FISH_COUNT * this.width / 500 * this.height / 500; this.$canvas.attr({width : this.width, height : this.height}); this.reverse = false; this.fishes.push(new FISH(this)); this.createSurfacePoints(); }, watchWindowSize : function(){ this.clearTimer(); this.tmpWidth = this.$window.width(); this.tmpHeight = this.$window.height(); this.watchIds.push(setTimeout(this.jdugeToStopResize, this.WATCH_INTERVAL)); }, clearTimer : function(){ while(this.watchIds.length > 0){ clearTimeout(this.watchIds.pop()); } }, jdugeToStopResize : function(){ var width = this.$window.width(), height = this.$window.height(), stopped = (width == this.tmpWidth && height == this.tmpHeight); this.tmpWidth = width; this.tmpHeight = height; if(stopped){ this.setup(); } }, bindEvent : function(){ this.$window.on('resize', this.watchWindowSize); this.$container.on('mouseenter', this.startEpicenter); this.$container.on('mousemove', this.moveEpicenter); this.$container.on('click', this.reverseVertical); }, getAxis : function(event){ var offset = this.$container.offset(); return { x : event.clientX - offset.left + this.$window.scrollLeft(), y : event.clientY - offset.top + this.$window.scrollTop() }; }, startEpicenter : function(event){ this.axis = this.getAxis(event); }, moveEpicenter : function(event){ var axis = this.getAxis(event); if(!this.axis){ this.axis = axis; } this.generateEpicenter(axis.x, axis.y, axis.y - this.axis.y); this.axis = axis; }, generateEpicenter : function(x, y, velocity){ if(y < this.height / 2 - this.THRESHOLD || y > this.height / 2 + this.THRESHOLD){ return; } var index = Math.round(x / this.pointInterval); if(index < 0 || index >= this.points.length){ return; } this.points[index].interfere(y, velocity); }, reverseVertical : function(){ this.reverse = !this.reverse; for(var i = 0, count = this.fishes.length; i < count; i++){ this.fishes[i].reverseVertical(); } }, controlStatus : function(){ for(var i = 0, count = this.points.length; i < count; i++){ this.points[i].updateSelf(); } for(var i = 0, count = this.points.length; i < count; i++){ this.points[i].updateNeighbors(); } if(this.fishes.length < this.fishCount){ if(--this.intervalCount == 0){ this.intervalCount = this.MAX_INTERVAL_COUNT; this.fishes.push(new FISH(this)); } } }, render : function(){ requestAnimationFrame(this.render); this.controlStatus(); this.context.clearRect(0, 0, this.width, this.height); this.context.fillStyle = 'hsl(0, 0%, 95%)'; for(var i = 0, count = this.fishes.length; i < count; i++){ this.fishes[i].render(this.context); } this.context.save(); this.context.globalCompositeOperation = 'xor'; this.context.beginPath(); this.context.moveTo(0, this.reverse ? 0 : this.height); for(var i = 0, count = this.points.length; i < count; i++){ this.points[i].render(this.context); } this.context.lineTo(this.width, this.reverse ? 0 : this.height); this.context.closePath(); this.context.fill(); this.context.restore(); } }; var SURFACE_POINT = function(renderer, x){ this.renderer = renderer; this.x = x; this.init(); }; SURFACE_POINT.prototype = { SPRING_CONSTANT : 0.03, SPRING_FRICTION : 0.9, WAVE_SPREAD : 0.3, ACCELARATION_RATE : 0.01, init : function(){ this.initHeight = this.renderer.height * this.renderer.INIT_HEIGHT_RATE; this.height = this.initHeight; this.fy = 0; this.force = {previous : 0, next : 0}; }, setPreviousPoint : function(previous){ this.previous = previous; }, setNextPoint : function(next){ this.next = next; }, interfere : function(y, velocity){ this.fy = this.renderer.height * this.ACCELARATION_RATE * ((this.renderer.height - this.height - y) >= 0 ? -1 : 1) * Math.abs(velocity); }, updateSelf : function(){ this.fy += this.SPRING_CONSTANT * (this.initHeight - this.height); this.fy *= this.SPRING_FRICTION; this.height += this.fy; }, updateNeighbors : function(){ if(this.previous){ this.force.previous = this.WAVE_SPREAD * (this.height - this.previous.height); } if(this.next){ this.force.next = this.WAVE_SPREAD * (this.height - this.next.height); } }, render : function(context){ if(this.previous){ this.previous.height += this.force.previous; this.previous.fy += this.force.previous; } if(this.next){ this.next.height += this.force.next; this.next.fy += this.force.next; } context.lineTo(this.x, this.renderer.height - this.height); } }; var FISH = function(renderer){ this.renderer = renderer; this.init(); }; FISH.prototype = { GRAVITY : 0.4, init : function(){ this.direction = Math.random() < 0.5; this.x = this.direction ? (this.renderer.width + this.renderer.THRESHOLD) : -this.renderer.THRESHOLD; this.previousY = this.y; this.vx = this.getRandomValue(4, 10) * (this.direction ? -1 : 1); if(this.renderer.reverse){ this.y = this.getRandomValue(this.renderer.height * 1 / 10, this.renderer.height * 4 / 10); this.vy = this.getRandomValue(2, 5); this.ay = this.getRandomValue(0.05, 0.2); }else{ this.y = this.getRandomValue(this.renderer.height * 6 / 10, this.renderer.height * 9 / 10); this.vy = this.getRandomValue(-5, -2); this.ay = this.getRandomValue(-0.2, -0.05); } this.isOut = false; this.theta = 0; this.phi = 0; }, getRandomValue : function(min, max){ return min + (max - min) * Math.random(); }, reverseVertical : function(){ this.isOut = !this.isOut; this.ay *= -1; }, controlStatus : function(context){ this.previousY = this.y; this.x += this.vx; this.y += this.vy; this.vy += this.ay; if(this.renderer.reverse){ if(this.y > this.renderer.height * this.renderer.INIT_HEIGHT_RATE){ this.vy -= this.GRAVITY; this.isOut = true; }else{ if(this.isOut){ this.ay = this.getRandomValue(0.05, 0.2); } this.isOut = false; } }else{ if(this.y < this.renderer.height * this.renderer.INIT_HEIGHT_RATE){ this.vy += this.GRAVITY; this.isOut = true; }else{ if(this.isOut){ this.ay = this.getRandomValue(-0.2, -0.05); } this.isOut = false; } } if(!this.isOut){ this.theta += Math.PI / 20; this.theta %= Math.PI * 2; this.phi += Math.PI / 30; this.phi %= Math.PI * 2; } this.renderer.generateEpicenter(this.x + (this.direction ? -1 : 1) * this.renderer.THRESHOLD, this.y, this.y - this.previousY); if(this.vx > 0 && this.x > this.renderer.width + this.renderer.THRESHOLD || this.vx < 0 && this.x < -this.renderer.THRESHOLD){ this.init(); } }, render : function(context){ context.save(); context.translate(this.x, this.y); context.rotate(Math.PI + Math.atan2(this.vy, this.vx)); context.scale(1, this.direction ? 1 : -1); context.beginPath(); context.moveTo(-30, 0); context.bezierCurveTo(-20, 15, 15, 10, 40, 0); context.bezierCurveTo(15, -10, -20, -15, -30, 0); context.fill(); context.save(); context.translate(40, 0); context.scale(0.9 + 0.2 * Math.sin(this.theta), 1); context.beginPath(); context.moveTo(0, 0); context.quadraticCurveTo(5, 10, 20, 8); context.quadraticCurveTo(12, 5, 10, 0); context.quadraticCurveTo(12, -5, 20, -8); context.quadraticCurveTo(5, -10, 0, 0); context.fill(); context.restore(); context.save(); context.translate(-3, 0); context.rotate((Math.PI / 3 + Math.PI / 10 * Math.sin(this.phi)) * (this.renderer.reverse ? -1 : 1)); context.beginPath(); if(this.renderer.reverse){ context.moveTo(5, 0); context.bezierCurveTo(10, 10, 10, 30, 0, 40); context.bezierCurveTo(-12, 25, -8, 10, 0, 0); }else{ context.moveTo(-5, 0); context.bezierCurveTo(-10, -10, -10, -30, 0, -40); context.bezierCurveTo(12, -25, 8, -10, 0, 0); } context.closePath(); context.fill(); context.restore(); context.restore(); this.controlStatus(context); } }; $(function(){ RENDERER.init(); });