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
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值