zoukankan      html  css  js  c++  java
  • python中的异常处理

    异常处理

    1.什么是异常?
    • 异常就是程序运行时发生错误的信号,异常发生之后的代码就不执行了
    2.python中的常见异常种类:
        AttributeError 试图访问一个对象没有的属性,比如foo.x,但foo没有属性x
        
        IOError 输入/输出异常;基本上是无法打开文件
        
        ImportError 无法引入模块或包;基本上是路径问题或名称错误
        
        IndentationError 语法错误(的子类) ;代码没有正确对齐
        
        IndexError 下标索引超出序列边界,比如列表x只有三个元素,却试图访问x[4]
        
        KeyError 试图访问字典里不存在的键
        
        KeyboardInterrupt Ctrl+C被按下
        
        NameError 使用一个还未被赋予对象的变量
        
        SyntaxError Python代码非法,代码不能编译
                                      
        TypeError 传入对象类型与要求的不符合
                                      
        UnboundLocalError 试图访问一个还未被设置的局部变量,基本上是由于另外有一个同名的全局变量,导致你以为正在访问它
                                      
        ValueError 传入一个调用者不期望的值,即使值的类型是正确的
    
    3.异常处理:
    	python解释器检测到错误时就会触发异常。
        
        如果异常触发后没被处理,程序就在当前异常处终止,后面的代码不会运行了。
        
        你可以编写异常处理的代码,专门用来捕捉这个异常,如果捕捉成功则进入另外一个处理分支,执行你为其定制的逻辑,使程序不会崩溃,这就是异常处理。
        
        异常是由程序的错误引起的,语法上的错误跟异常处理无关,必须在程序运行前就修正。
        
        
        
        一、使用if判断来进行异常处理:
        	
            num1=input('>>: ') #输入一个字符串试试
            if num1.isdigit():
                int(num1) #我们的正统程序放到了这里,其余的都属于异常处理范畴
            elif num1.isspace():
                print('输入的是空格,执行这里的逻辑')
            elif len(num1) == 0:
                print('输入的是空,执行这里的逻辑')
            else:
                print('其他情况,执行这里的逻辑')
    
      
            总结:
                1.if判断式的异常处理只能针对某一段代码,对于不同的代码段的相同类型的错误你需要写重复的if来进行处理。
    
                2.在你的程序中频繁的写与程序本身无关,与异常处理有关的if,会使得你的代码可读性极其的差
                
                
         二、python为每一种异常定制了一个类型,然后提供了一种特定的语法结构用来进行异常处理
        
        	【1】:基本语法
                
                try:
                     被检测的代码块
                except 异常类型:
                     代码块		#try中一旦检测到异常,就执行这个位置的逻辑
                    
                #示例1:
                l1 = [11,22,33,44,55,66,77,88,99,1111,1133,15652]
                obj = iter(l1)   # 将可迭代对象转化成迭代器
                while 1:
                    try:
                        print(next(obj))
                    except StopIteration:
                        break
                #示例2:        
                f = open('pick多数据',mode='rb')
                while True:
                    try:
                        print(pickle.load(f))
                    except EOFError:
                        break
                f.close()
                        
          	【2】异常类只能用来处理指定的异常情况,如果非指定异常则无法处理。
            
            	# 未捕获到异常,程序直接报错
                s1 = 'hello world'
                try:
                    int(s1)
                except IndexError as e:
                    print(e)
                
                #结果:ValueError: invalid literal for int() with base 10: 'hello world'
                    
                    
             
            【3】多分支
            
            	s1 = 'hello world'
                try:
                    int(s1)
                except IndexError as e:
                    print(e)
                except KeyError as e:
                    print(e)
                except ValueError as e:
                    print(e)
                    
                #结果:invalid literal for int() with base 10: 'hello world'
                
             【4】万能异常
            
            	s1 = 'hello world'
                try:
                    int(s1)
                except Exception as e:
                    print(e)
                #结果:
                invalid literal for int() with base 10: 'hello world'
                    
                    1.如果你想要的效果是,无论出现什么异常,我们统一丢弃,或者使用同一段代码逻辑去处理他们,那么只有一个Exception就足够了。
    
                        s1 = 'hello world'
                        try:
                            int(s1)
                        except Exception as e:
                            print(e)	#丢弃或者执行其他逻辑
    
                        #如果你统一用Exception可以捕捉所有异常,但你在处理所有异常时都必须使用同一个逻辑去处理(这里说的逻辑即当前expect下面的代码块)
    
                    2.如果你想要的效果是,对于不同的异常我们需要定制不同的处理逻辑,那就需要用到多分支了。
                        #多分支:
                        s1 = 'hello world'
                        try:
                            int(s1)
                        except IndexError as e:
                            print(e)
                        except KeyError as e:
                            print(e)
                        except ValueError as e:
                            print(e)
    
                        #多分支 + Exception
                        s1 = 'hello world'
                        try:
                            int(s1)
                        except IndexError as e:
                            print(e)
                        except KeyError as e:
                            print(e)
                        except ValueError as e:
                            print(e)
                        except Exception as e:
                            print(e)
                            
    	    【5】异常的其他结构:
                
                	s1 = 'hello'
                    try:
                        int(s1)
                    except IndexError as e:
                        print(e)
                    except KeyError as e:
                        print(e)
                    except ValueError as e:
                        print(e)
                    else:
                        print('try内代码块没有异常则执行此代码')
                    finally:
                        print('无论异常与否,都会执行此代码,通常是进行清理工作')
                        
               【6】主动触发异常/主动抛异常
                
                    try:
                        raise TypeError('类型错误')
                    except Exception as e:
                        print(e)
                        
               【7】自定义异常
              
                    class My_Exception(BaseException):
                        def __init__(self,msg):
                            self.msg=msg
                        def __str__(self):
                            return self.msg
    
                    try:
                        raise My_Exception('类型错误')
                        
                    except My_Exception as e:
                        print(e)
                        
              【8】:断言
                    # assert 条件
    
                    assert 1 == 1
    
                    assert 1 == 2
                    
              【9】小结:
            
            	使用try..except的方式:
    
                    1:把错误处理和真正的工作分开来;
                    2:代码更易组织,更清晰,复杂的工作任务更容易实现;
                    3:毫无疑问更安全了,不至于由于一些小的疏忽而使程序意外崩溃了;
                
                什么时候用异常处理?
                    try...except应该尽量少用,因为它本身就是你附加给你的程序的一种异常处理的逻辑,与你的主要的工作是没有关系的。
                    加多了,会导致你的代码可读性变差,只有在有些异常无法预知的情况下,才应该加上try...except,其他的逻辑错误应该尽量修正。
    
  • 相关阅读:
    python3.x 基础五:模块
    python3.x 基础四:目录获取及目录规范
    python3.x 基础四:json与pickple
    python3.x 基础四:生成器与迭代器
    python3.x 基础三:装饰器
    python3.x 基础三:函数
    [leetcode]Anagrams
    [leetcode]Text Justification
    [leetcode]Single Number
    [leetcode]Longest Palindromic Substring
  • 原文地址:https://www.cnblogs.com/xiaomage666/p/11111225.html
Copyright © 2011-2022 走看看