python笔记-08(异常)

一些常用的内置异常类

使用raise可以抛出异常类:raise Exception("xxxxxx") 。

1、自定义异常类

和java类似,自定义异常类时需要直接或间接继承Exception类。

# 测试异常


# 自定义异常类
class MyException(Exception):
    pass

2、捕获异常

# 在调用其他人的方法时,可以使用try except进行异常的捕获
# 如果不捕获异常将会向上传播
try:
    x = int(input("please input the first number:"))
    y = int(input("please input the second number:"))
    print("x / y = ", x / y)
except Exception:
    print("has exception")

结果
please input the first number:12
please input the second number:0
has exception

3、捕获异常与抛出异常

# 在处理异常的语句中可以选择继续抛出该异常或者抛出其他异常
class ExceptionTest:
    flag = False

    def setFlag(self, flag):
        ExceptionTest.flag = flag

    def method(self):
        try:
            x = int(input("please input the first number:"))
            y = int(input("please input the second number:"))
            print("x / y = ", x / y)
        except ZeroDivisionError:
            if ExceptionTest.flag:
                print("can't div by zero")
            else:
                raise ValueError


exceptionTest = ExceptionTest()
# 设置为False,异常将会被抛出
exceptionTest.setFlag(True)
exceptionTest.method()

结果
please input the first number:12
please input the second number:0
can't div by zero

 4、捕获多个异常

try块中可能不止除0异常,输入的可能不是数字导致转换成数字时发生错误。所以可使用多个except对异常进行捕获。

# 捕获多个异常
class ExceptionTest:
    flag = False

    def setFlag(self, flag):
        ExceptionTest.flag = flag

    def method(self):
        try:
            x = int(input("please input the first number:"))
            y = int(input("please input the second number:"))
            print("x / y = ", x / y)
        except ZeroDivisionError:
            if ExceptionTest.flag:
                print("can't div by zero")
            else:
                raise ValueError
        except ValueError:
            if ExceptionTest.flag:
                print("the number must be numerical")
            else:
                raise ValueError


exceptionTest = ExceptionTest()
exceptionTest.setFlag(True)
exceptionTest.method()

结果
please input the first number:12
please input the second number:s
the number must be numerical

捕获多个异常时还可以为如下方式,将多个异常写在括号中,同时将异常赋值给一个对象

# 捕获多个异常的修改版
class ExceptionTest:
    flag = False

    def setFlag(self, flag):
        ExceptionTest.flag = flag

    def method(self):
        try:
            x = int(input("please input the first number:"))
            y = int(input("please input the second number:"))
            print("x / y = ", x / y)
        # 通常可以使用except Exception as e对异常进行捕获。
        # 因为Exception的基类为BaseException,所以对于继承BaseException的子类可能不能被捕获到
        # 还可以使用 except: 来捕获异常但是这样比较危险不推荐使用。
        except (ZeroDivisionError, ValueError) as e:
            if ExceptionTest.flag:
                print("the number has some wrong")
                # 捕获异常对象并打印
                print(e)
            else:
                raise ValueError


exceptionTest = ExceptionTest()
exceptionTest.setFlag(True)
exceptionTest.method()

 5、else与finally

使用finall的最主要原因为在发生异常之后可以对一些资源进行关闭,例如网络资源,IO资源。

# 异常处理中的else与finally
# 在未发生异常时,会执行else中的语句,不管程序发不发生异常都会执行finally中的语句
class ExceptionTest:
    flag = False

    def setFlag(self, flag):
        ExceptionTest.flag = flag

    def method(self):
        try:
            x = int(input("please input the first number:"))
            y = int(input("please input the second number:"))
            print("x / y = ", x / y)
        except (ZeroDivisionError, ValueError) as e:
            if ExceptionTest.flag:
                print("the number has some wrong")
                # 捕获异常对象并打印
                print(e)
            else:
                raise ValueError
        else:
            print("未发生异常")
        finally:
            print("进行清理工作")


exceptionTest = ExceptionTest()
exceptionTest.setFlag(True)
exceptionTest.method()

结果
please input the first number:12
please input the second number:0
the number has some wrong
division by zero
进行清理工作

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python中,异常处理是非常重要的一部分。当程序运行时如果出现错误,如果没有异常处理,程序就会崩溃。为了避免这种情况,Python提供了异常处理机制。 在Python中,异常处理语句使用 `try` 和 `except` 关键字来实现。`try` 语句块中包含可能会发生异常的代码,如果这段代码出现了异常,则会跳转到 `except` 语句块中执行异常处理代码。 下面是一个简单的例子: ```python try: num = int(input("请输入一个整数:")) print(10/num) except ZeroDivisionError: print("除数不能为0") except ValueError: print("输入的不是整数") ``` 在上面的代码中,我们尝试将用户输入的字符串转换为整数,并将其用作除数计算 10/num。如果用户输入的是 0,则会触发 ZeroDivisionError 异常。如果用户输入的不是整数,则会触发 ValueError 异常。如果发生异常,则会跳转到对应的 except 语句块中执行处理代码。 除了可以指定具体的异常类型,也可以使用 `except Exception` 来捕获所有异常。例如: ```python try: num = int(input("请输入一个整数:")) print(10/num) except Exception as e: print("发生异常:", e) ``` 在上面的代码中,如果发生任何异常,都会跳转到 `except` 语句块中执行处理代码,并将异常信息打印出来。 除了 `try` 和 `except`,还有 `finally` 关键字,它指定的代码块无论是否发生异常都会执行。例如: ```python try: num = int(input("请输入一个整数:")) print(10/num) except Exception as e: print("发生异常:", e) finally: print("程序执行完毕") ``` 在上面的代码中,无论是否发生异常,都会执行 `finally` 中的代码,即输出“程序执行完毕”。 总之,在Python中,异常处理是非常重要的一部分,它可以有效避免程序崩溃,提高程序的健壮性和可靠性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值