python 异常捕获

异常捕获

在python程序中,我们需要让代码输出异常

在代码中异常是可以捕获的,但是错误无法被捕获

所以我们现在是在捕获异常


#捕获异常

try:
    with open('testq123') as f :
        pass
except :
    print ('cuowu')

print ('cuowu1')

#输出什么?文件不存在的情况下
输出:
cuowu
cuowu1

#此时就是异常而不是错误,

def of1():
    try:
        print ('test1')
        c = 1/0 #除零异常
        print ('test2')
    except:
        print('whwhw')

    print ('who?')

 of1()

#会输出什么?当除零异常后会在继续执行 print(‘test2’)的语句吗?
输出:
test1
whwhw
who?
#从此我们发现我们的try 是一个捕获异常的语句,当try中语句出现异常他会输出except的语句。
#那么except 她又能捕获什么异常呢?


#针对捕获类型


def foo():
   try:
       print ('test1')
       c = 1/0
       print ('test2')
   except ArithmeticError: #指定捕获类型
       print ('who')
   print ('who?')

foo()

#捕获类型为ArithmeticError计算错误,里面吗包含了
# +-- FloatingPointError
#      |   +-- OverflowError
#      |   +-- ZeroDivisionError
#这个东西需要联系后边才能得心应手
#python 错误类型
# Python异常的继承
# BaseException
#  +-- SystemExit
#  +-- KeyboardInterrupt
#  +-- GeneratorExit
#  +-- Exception
#      +-- RuntimeError
#      |   +-- RecursionError
#      +-- MemoryError
#      +-- NameError
#      +-- StopIteration
#      +-- StopAsyncIteration
#      +-- ArithmeticError
#      |   +-- FloatingPointError
#      |   +-- OverflowError
#      |   +-- ZeroDivisionError
#      +-- LookupError
#      |   +-- IndexError
#      |   +-- KeyError
#      +-- SyntaxError
#      +-- OSError
#      |   +-- BlockingIOError
#      |   +-- ChildProcessError
#      |   +-- ConnectionError
#      |   |   +-- BrokenPipeError
#      |   |   +-- ConnectionAbortedError
#      |   |   +-- ConnectionRefusedError
#      |   |   +-- ConnectionResetError
#      |   +-- FileExistsError
#      |   +-- FileNotFoundError
#      |   +-- InterruptedError
#      |   +-- IsADirectoryError
#      |   +-- NotADirectoryError
#      |   +-- PermissionError
#      |   +-- ProcessLookupError
#      |   +-- TimeoutError

import sys #引入系统模块需要使用

#测试
print ('test----1')
sys.exit(1)
print ('test----2') #是否执行


try:
   print ('test1')
   sys.exit(1)
   print('test2') #是否能够执行
except SystemExit:
   print ('test3')
print ('test4')#是否能够执行

#当指定异常类型那么捕获会不会生效,又有什么作用??
输出:
test1
test3
test4

#他会输出 1 3 4 但是不会输出 2 那么就说明异常已经捕获

#exception是所有内建的,非系统退出的异常的基类(父类),自定义异常都应该继承于他
def a()
    try:
        a5 = 0
    except :
        print ('11')

#python将这种错误也归到异类exception的子类中,但是这种错误他是不可捕获的


#我们做一个终结参数
import  time

try:
    while True:
        time.sleep(1)
        print ('running')
except KeyboardInterrupt: #键值终端
    print ("Ctrl + C")
print ('**' * 30 )

#原理就是try里一个死循环然后每隔一秒输出running

#ArithmeticError 所有算术的异常捕获 之前使用过在除零异常中

#lookupErroe 使用映射的键或者序列索引无效时引发的基类异常,index Error key Error

#那么我们知道exception 是所有错误的基类,那么我们就可以自定义错误类。

class MyException(Exception): #自定义错误类
    pass

try:

    raise MyException()

except MyException:

    print ('chuci')

#Exception源码
class Exception(BaseException):
    """ Common base class for all non-exit exceptions. """
    def __init__(self, *args, **kwargs): # real signature unknown
        pass

    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass


class ArithmeticError(Exception):
    """ Base class for arithmetic errors. """
    def __init__(self, *args, **kwargs): # real signature unknown
        pass

    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass


class AssertionError(Exception):
    """ Assertion failed. """
    def __init__(self, *args, **kwargs): # real signature unknown
        pass

    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass


class AttributeError(Exception):
    """ Attribute not found. """
    def __init__(self, *args, **kwargs): # real signature unknown
        pass

    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass


class WindowsError(Exception):
    """ Base class for I/O related errors. """
    def __init__(self, *args, **kwargs): # real signature unknown
        pass

    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __reduce__(self, *args, **kwargs): # real signature unknown
        pass

    def __str__(self, *args, **kwargs): # real signature unknown
        """ Return str(self). """
        pass

    characters_written = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    errno = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """POSIX exception code"""

    filename = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """exception filename"""

    filename2 = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """second exception filename"""

    strerror = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """exception strerror"""

    winerror = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """Win32 exception code"""

#可以看到exception还有基类(BaseException),里面写了魔术方法,这就是底层源码了,包括增删改查初始化

 class BaseException(object):
    """ Common base class for all exceptions """
    def with_traceback(self, tb): # real signature unknown; restored from __doc__
        """
        Exception.with_traceback(tb) --
            set self.__traceback__ to tb and return self.
        """
        pass

    def __delattr__(self, *args, **kwargs): # real signature unknown
        """ Implement delattr(self, name). """
        pass

    def __getattribute__(self, *args, **kwargs): # real signature unknown
        """ Return getattr(self, name). """
        pass

    def __init__(self, *args, **kwargs): # real signature unknown
        pass

    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __reduce__(self, *args, **kwargs): # real signature unknown
        pass

    def __repr__(self, *args, **kwargs): # real signature unknown
        """ Return repr(self). """
        pass

    def __setattr__(self, *args, **kwargs): # real signature unknown
        """ Implement setattr(self, name, value). """
        pass

    def __setstate__(self, *args, **kwargs): # real signature unknown
        pass

    def __str__(self, *args, **kwargs): # real signature unknown
        """ Return str(self). """
        pass

    args = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    __cause__ = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """exception cause"""

    __context__ = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """exception context"""

    __suppress_context__ = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    __traceback__ = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default


    __dict__ = None # (!) real value is "mappingproxy({'__repr__': <slot wrapper '__repr__' of 'BaseException' objects>, '__str__': <slot wrapper '__str__' of 'BaseException' objects>, '__getattribute__': <slot wrapper '__getattribute__' of 'BaseException' objects>, '__setattr__': <slot wrapper '__setattr__' of 'BaseException' objects>, '__delattr__': <slot wrapper '__delattr__' of 'BaseException' objects>, '__init__': <slot wrapper '__init__' of 'BaseException' objects>, '__new__': <built-in method __new__ of type object at 0x00007FFE2F3E4F50>, '__reduce__': <method '__reduce__' of 'BaseException' objects>, '__setstate__': <method '__setstate__' of 'BaseException' objects>, 'with_traceback': <method 'with_traceback' of 'BaseException' objects>, '__suppress_context__': <member '__suppress_context__' of 'BaseException' objects>, '__dict__': <attribute '__dict__' of 'BaseException' objects>, 'args': <attribute 'args' of 'BaseException' objects>, '__traceback__': <attribute '__traceback__' of 'BaseException' objects>, '__context__': <attribute '__context__' of 'BaseException' objects>, '__cause__': <attribute '__cause__' of 'BaseException' objects>, '__doc__': 'Common base class for all exceptions'})"





#看完那一套复杂的 我们看一下简单的那就是finally,这是一个始终会输出的语句,就算是捕获到异常他也会输出为了一些必要操作


try:
     p =  open('D:\syslog.txt')
except FileExistsError as e :
    print ('{} {} {} '.format(e.__class__,e.errno,e.strerror))
finally:
    print ('worker stop ')
    p.close()


    
#也可以加一些条件判断,做一些抉择    
try:
     p =  open('D:\syslog.txt')
except FileExistsError as e :
    print ('{} {} {} '.format(e.__class__,e.errno,e.strerror))
finally:
    print ('worker stop ')
    if p :
        p.close()

#也可以在finally中再捕获异常然后在输出
        

try:
    f = open('D:\syslog.txt')
except FileExistsError as e :
    print ('{}'.format(e))
finally:
     print ('worker stop')
     try:
         f.close()
     except Exception as e :
         print (e)


#也可以在try中套try进行输出


try:
    try:
        i = 1/0
    except KeyError as e :
        print (1,e)
    finally:
        print (2,'worker ')
except FileNotFoundError as e :
    print (3,e)
finally:
    print (4,'worker inine ')
    
    
    
try:
    ret = 1 * 0
except ArithmeticError as e :
    print ('{}'.format(e))
else:
     print( 'os')
finally:
    print ('worker init')



#多种异常捕获

class MyException(Exception):
	pass


try:
    a = 1/0
    raise  MyException()
    open('t')
    sys.exit(1)
except ZeroDivisionError as e :
    print ('除零异常')
except ArithmeticError as e :
    print ('Ari error')
except MyException as e :
    print ('my error')
except  Exception as e :
    print ('Exception ')
except :
    print ('default error')


print ('end -----------')

#他会先raise 然后再输出错误数据,匹配到除零异常。
#捕获规则
#1.捕获是从上到下依次匹配,匹配则输出except
#2.如果被一个except捕获,那么其他的except就不会再捕获了
#3.如果没有捕获到异常则会向外层抛出
#4.expect为缺省捕获,最后一个必须为缺省防止向外层抛出


#捕获规则,从小打到,从具体到	宽泛

class A:pass


try:
    1/0
    raise A
    raise A()
    raise  1
    raise "abc"
except Exception as e :
    print (type(e),e)

#as 到底输出什么?
#raise 后要求应该是baseEXception类的子类或实例,如果是类则需要被无参实例化,自定义应该是exception的子类
#raise 后什么都没有,抛出一个已经被激活的类,如果没有被激活的异常,则抛出类型异常。




总结:
try 
	#运行代码
except #异常类
	#捕获某种类型的异常
except #异常类 as 变量名称
 	#捕获某种异常类的对象
else 
	#如果没有发生异常需要执行的语句
finally 
	#推出try需要执行的语句
    
#工作原理   
#1.如果try中发生异常会搜索except子句,并执行匹配的第一个的异常子句
#2.如果try中发生异常并没有匹配的except子句,那则会向外层try抛出,如果始终没有被捕获则会终止异常线程
#3.如果try中没有发生异常,则会执行else语句。
#4.无论try中有无异常finally都会执行。



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值