python第八章处理异常

news/2025/2/1 9:12:44 标签: python

设置特定异常提示语:

#单独作用
try:
    x=int(input('enter the first:'))
    y=int(input('enter the second:'))
    print(x/y)
except  ZeroDivisionError:
    print("the second number can't be zero")

enter the first:12
enter the second:0
the second number can't be zero
#写进类型
class muffledcal:
    muffled=False
    def cal(self,expr):
        try:
            return eval(expr)
        except ZeroDivisionError:
            if self.muffled:
                print('division by zero')
            else:
                raise

calculator=muffledcal()
calculator.cal('10/2')
5.0

calculator.cal('10/0')
Traceback (most recent call last):
  File "<pyshell#42>", line 1, in <module>
    calculator.cal('10/0')
  File "<pyshell#30>", line 5, in cal
    return eval(expr)

calculator.muffled=True
calculator.cal('10/0')
division by zero
  File "<string>", line 1, in <module>
ZeroDivisionError: division by zero

 所有错误均显示同样:

try:  
x = int(input('Enter the first number: ')) 
y = int(input('Enter the second number: ')) 
print(x / y) 
except: 
  print('Something wrong happened ...') 

没引发错误时跳出循环:

while True:  
    try: 
         x = int(input('Enter the first number: ')) 
         y = int(input('Enter the second number: ')) 
         value = x / y 
         print('x / y is', value) 
    except: 
         print('Invalid input. Please try again.') 
    else: 
         break 

无论有无错误都结束:

    x = None 
    try:  
        x = 1 / 0 
    finally: 
        print('Cleaning up ...') 
        del x 

检查有无赋值的高效做法:

#低效
def describe_person(person): 
    print('Description of', person['name']) 
    print('Age:', person['age']) 
    if 'occupation' in person:  
         print('Occupation:', person['occupation']) 
#高效
def describe_person(person): 
    print('Description of', person['name']) 
    print('Age:', person['age']) 
    try: 
        print('Occupation:', person['occupation'])  
        except KeyError: pass 

过滤警告:

from warnings import filterwarnings
filterwarnings("ignore")    #过滤ignore类型的警告
from warnings import warn
warn("anyone out there?")

raise使用:

#处理错误并报出错误类型
eval=None

try:
    print(eval=10/0)
except ZeroDivisionError:
    print('10/2')
    raise

10/2
Traceback (most recent call last):
  File "<pyshell#67>", line 2, in <module>
    print(eval=10/0)
ZeroDivisionError: division by zero
#自定义特定类型错误,raise该类型错误       
class detailed(Exception):    #detailed为一种类型的错误
    def __init__(self,message,code,severity):
        super().__init__(message)    #super获取超类
        self.code=code
        self.severity=severity

        
def some_function(condition):
    if condition:
        raise detailed("Detailed error description: The specified condition has been met.", 400, "error")    #触发错误
    return "Function executed successfully without raising an error."

try:
    result=some_function(True)    #触发错误,执行except
except detailed as e:
    print(f"caught a detailederror:{e}")
    print(f"error code:{e.code}")
    print(f"severity:{e.severity}")
else:
    print(result)

    
caught a detailederror:Detailed error description: The specified condition has been met.
error code:400
severity:error    


http://www.niftyadmin.cn/n/5839243.html

相关文章

面试之SolrElasticsearch

优点&#xff1a; 1.Elasticsearch是分布式的。不需要其他组件&#xff0c;分发是实时的&#xff0c;被叫做”Push replication”。 2.Elasticsearch 完全支持 Apache Lucene 的接近实时的搜索。 3.处理多租户&#xff08;multitenancy&#xff09;不需要特殊配置&#xff0…

Vue 3 30天精进之旅:Day 10 - Vue Router

在现代单页面应用&#xff08;SPA&#xff09;中&#xff0c;路由管理是必不可少的一部分。Vue Router是Vue.js官方的路由管理库&#xff0c;它使得在Vue应用中实现路由变得简单而灵活。今天的学习将围绕以下几个方面展开&#xff1a; Vue Router概述安装和基本配置定义路由路…

项目练习:重写若依后端报错cannot be cast to com.xxx.model.LoginUser

文章目录 一、情景说明二、解决办法 一、情景说明 在重写若依后端服务的过程中 使用了Redis存放LoginUser对象数据 那么&#xff0c;有存就有取 在取值的时候&#xff0c;报错 二、解决办法 方法1、在TokenService中修改如下 getLoginUser 方法中&#xff1a;LoginUser u…

Kafka常见问题之 java.io.IOException: Disk error when trying to write to log

文章目录 Kafka常见问题之 java.io.IOException: Disk error when trying to write to log1. 问题概述2. 问题排查方向&#xff08;1&#xff09;磁盘空间不足&#xff08;2&#xff09;磁盘 I/O 故障&#xff08;3&#xff09;Kafka 日志文件损坏&#xff08;4&#xff09;Kaf…

Java设计模式:行为型模式→观察者模式

Java 观察者模式详解 1. 定义 观察者模式&#xff08;Observer Pattern&#xff09;是一种行为型设计模式&#xff0c;它定义了一种一对多的依赖关系&#xff0c;使得当一个对象的状态发生变化时&#xff0c;所有的依赖者&#xff08;观察者&#xff09;都会得到通知并自动更…

C++计算给定序列在多次修改前后满足特定条件的极大匹配方案的大小

给定长度为n的整数序列 a 1 , a 2 , . . . , a n a_1,a_2,...,a_n a1​,a2​,...,an​和长度为n的01序列 b 1 , b 2 , . . . , b n b_1,b_2,...,b_n b1​,b2​,...,bn​。 对于 1 ≤ i < j ≤ n 1\leq i<j\leq n 1≤i<j≤n&#xff0c;称二元组 ( i , j ) (i,j) (i,j)…

conda配置channel

你收到 CondaKeyError: channels: value https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main not present in config 错误是因为该镜像源&#xff08;https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main&#xff09;可能没有被正确添加到 Conda 的配置文件中&…

解决运行npm时报错

在运行一个Vue项目时报错&#xff0c;产生下面问题 D:\node\npm.cmd run dev npm WARN logfile could not be created: Error: EPERM: operation not permitted, open D:\node\node_cache\_logs\2025-01-31T01_01_58_076Z-debug-0.log npm WARN logfile could not be created:…