Python初识异常处理

目录

  • 什么是异常与异常处理
  • 异常的语法结构

什么是异常与异常处理

  • 异常就是错误
  • 异常会导致程序崩溃并停止运往
  • 能监控并捕获到异常,将异常部位的程序进行修理使得程序继续正常运行

异常的语法

  • 异常语法


  • 异常抛出


  • 异常捕获


捕获通用异常

  • 无法确定是哪种异常的情况下使用的捕获方法
try:
    <代码块>
except Exception as e:
    <异常代码块>

捕获具体异常

  • 确定是哪种异常的情况下使用的捕获方法
  • except<具体的异常类型>as e
  • ZeroDivisionError是python内置的具体异常:0不能被整除

捕获多个异常

  • 当except代码块有多个的时候,当捕获到第一个后,不会继续往下捕获
  • 方法一
try:
    print('try start')
    res = 1/0
    print('try finish')
except ZeroDivisionError as e:
    print(e)
except Exception as e:  # 可以有多个except
    print( 'this is a public exctept, bug is :%s' % e)
  • 方法二
try:
    print('try start')
    res = 1/0
    print('try finish')
except (ZeroDivisionError,Excception) as e:
    print(e)

实战

#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time     : 2021/8/16 21:41
# @Author   : InsaneLoafer
# @File     : try_init.py

def upper(str_data):
    new_str = 'None'
    try:
        new_str = str_data.upper()
    except Exception as e:
        print('程序出错了:{}'.format(e))
    return new_str


result = upper(1)  # 如果没有try会抛出异常:AttributeError: 'int' object has no attribute 'upper'
print('result:', result)


def test():
    try:
        print('collo')
        1 / 0
        print('hello')  # 出错代码后面的代码不会执行
    except ZeroDivisionError as e:
        print(e)


test()

def test1():
    try:
        print('hello')
        print(name)
    except (ZeroDivisionError, NameError) as e:  # 捕获的异常类型不对,也会报错,可以使用元组来定义多个异常类型
        print(e)
        print(type(e))
        print(dir(e))

test1()
程序出错了:'int' object has no attribute 'upper'
result: None
collo
division by zero
hello
name 'name' is not defined
<class 'NameError'>
['__cause__', '__class__', '__context__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__suppress_context__', '__traceback__', 'args', 'with_traceback']

Process finished with exit code 0
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容