首页 > 编程语言 >Python - Strategies to handle exceptions in your code

Python - Strategies to handle exceptions in your code

时间:2024-07-31 20:51:05浏览次数:10  
标签:code handle Python LBYL EAFP error operation approach

There are two approaches that can be followed when we want to deal with exceptions that occur due to unusual events:

  1. LBYL - Look Before You Leap
  2. EAFP - Easier to Ask for Forgiveness than Permission

In the LBYL approach, we avoid exceptions, while in the EAFP approach, we handle exceptions.

First, let us see the “Look before You Leap” approach. In this approach, we use conditional checks to eliminate any possibility of error. Whenever we have to perform any error-prone operation, first, we make sure that all conditions are favorable for the execution of that operation. We check all the situations that can make the operation give errors and we do this by placing conditional checks in the form of if statements. When the conditions are favourable, then only we execute the operation. If there is any possibility of error, we do not execute the operation.

if girls == 0:
   print('No girls, Ratio not defined')
else:
   print('Ratio of boys to girls is', boys / girls)

So, we prevented the error from occurring by putting an if statement. In the LBYL approach, there will be a lot of checking done before the operation actually executes because we have to make sure that nothing goes wrong while performing that operation. That is why there will be lot of if statements when we write our error handling code using this coding style.

The other approach is EAFP, “Easier to ask for forgiveness than permission.” This is based on a famous quote by Grace Hooper. In this approach, we try to execute the code assuming that everything will work correctly, but if our assumption proves false and something goes wrong, we deal with it. Python supports this approach with the help of try…except statement. We will see the details of this statement in the coming sections.

try:
    print('Ratio of boys to girls is ', boys / girls)
except ZeroDivisionError:
    print('No girls, Ratio not defined')

In the LBYL approach, we are very cautious; we do not give Python a chance to raise the exception, while in EAFP, we just go ahead and execute the operation, and if anything unusual occurs and Python raises an exception, then we just handle that exception. From these two approaches, EAFP is more Pythonic; it is commonly used by Python programmers, while LBYL is common in other languages like C, which don’t have any exception-handling mechanism.

 

Let us compare the two approaches and see some benefits of using the EAFP approach.

Since exceptions are rare, the code will work correctly most of the time. In LBYL, all the if statements are processed every time the code is run, even when everything is okay. This increases the execution time. The extra conditions put extra overhead on code processing. In EAFP, the error handling mechanism is processed only when an exception occurs, not every time the code runs. So, this approach results in efficient running in usual cases when the error does not occur. We know that most of the time, errors do not occur, so using this approach results in better performance of our program. In LBYL, sometimes you must duplicate a part of the operation in the conditional check, which again results in extra processing.

Another advantage of the EAFP approach is that the error handling code does not get mixed with your mainstream code. The error handling code is separate from the mainstream code; the mainstream code is in one block, and the error handling code is in a separate block. This separation makes the program more readable and easier to debug or modify. In LBYL, the if statements are mixed with the main logic of the program. This reduces program clarity and readability and makes it difficult to understand or modify the program thus, code management becomes difficult. In EAFP, the emphasis is on the mainstream code, while in LBYL, the emphasis is on the conditions, and the main code gets rather hidden at the end, which is not good for program readability.

Sometimes it is not possible to predict exactly what errors can occur in an operation, or the programmer may miss checking some conditions. In those cases, it is better to attempt the operation and then catch the error.

Another problem with LBYL approach is that sometimes the circumstances can change between the looking and the leaping step, so when you checked the conditions, everything was fine but while attempting the operation, something goes wrong; this could happen in a multithreaded environment. If we use EAFP approach, there will be no such problem.

 

标签:code,handle,Python,LBYL,EAFP,error,operation,approach
From: https://www.cnblogs.com/zhangzhihui/p/18335454

相关文章

  • 全网最适合入门的面向对象编程教程:29 类和对象的Python实现-断言与防御性编程和help函
    全网最适合入门的面向对象编程教程:29类和对象的Python实现-断言与防御性编程和help函数的使用摘要:在Python中,断言是一种常用的调试工具,它允许程序员编写一条检查某个条件。本文主要介绍了断言的应用场景和特点以及assert语句的使用,同时介绍了防御性编程和help()函数......
  • Python入门知识点 10--闭包与装饰器
    一、直接与间接程序开发潜规则生活中:   有台电脑,他的硬盘空间不够了,里面的资料我不能动,也不能删,咋办   1.加装硬盘--直接解决--前提是我的电脑能加装   2.插个u盘--间接解决-->没有特别的要求,比较灵活   开发潜规则:   代码拓展-->开放-->可......
  • python log运算如何写
    Python中用于计算对数的log()方法,是Python入门基础中的必会的方法,需要的朋友可以参考下。log()方法返回x的自然对数,x>0。语法以下是log()方法的语法:import math math.log( x )注意:此函数是无法直接访问的,所以我们需要导入math模块,然后需要用math的静态对象来调用......
  • Python - operator module
    >>>list(map(lambdax,y:x*y,[1,2,3,4],[5,6,7,8]))[5,12,21,32]Herewehavecalledthemapfunctionandsentalambdaexpressionasfirstargument.Insteadofthelambdafunction,youcansendoperator.mul.>>>list(map(operator......
  • Python操作excel常用操作介绍,入门首选
            使用Python操作Excel文件有许多常用操作。以下是一些常见的操作及其简要描述,下面是全面详细的示例,展示如何使用Python操作Excel文件,我们将使用pandas和openpyxl库来进行各种操作。常用库pandas:用于数据分析和处理,支持读取和写入Excel文件。openpyxl:用于读......
  • Python蒙特卡罗(Monte Carlo)模拟计算投资组合的风险价值(VaR)
    原文链接:http://tecdat.cn/?p=22862原文出处:拓端数据部落公众号如何使用Python通过蒙特卡洛模拟自动计算风险值(VaR)来管理投资组合或股票的金融风险。金融和投资组合风险管理中的VaR?VaR是"风险价值"的缩写,是许多公司和银行用来确定其公司内部金融风险水平的工具。风险值是为......
  • Python 元类深析:定制类创建的高级工
    元类是Python中一个强大而高级的特性,它允许我们自定义类的创建过程。本文将详细介绍Python元类的概念、工作原理以及常见用途。一. 什么是元类简单来说,元类就是用来创建类的类。在Python中,类也是对象,而元类就是用来创建这些类对象的。我们知道类是用来创建对象的......
  • 代码随想录训练第三十天|01背包理论基础、01背包、LeetCode416.分割等和子集
    文章目录01背包理论基础01背包二维dp数组01背包一维dp数组(滚动数组)416.分割等和子集思路01背包理论基础背包问题的理论基础重中之重是01背包,一定要理解透!leetcode上没有纯01背包的问题,都是01背包应用方面的题目,也就是需要转化为01背包问题。所以我先通过纯01背......
  • 代码随想录训练第三十一天|LeetCode1049.最后一块石头的重量II、LeetCode494.目标和、
    文章目录1049.最后一块石头的重量II思路一维数组二维数组494.目标和思路一维数组解法二维数组解法474.一和零思路1049.最后一块石头的重量II有一堆石头,用整数数组stones表示。其中stones[i]表示第i块石头的重量。每一回合,从中选出任意两块石头,然后将它们一......
  • 代码随想录训练第三十二天|完全背包理论基础、LeetCode518.零钱兑换II、LeetCode377.
    文章目录完全背包理论基础完全背包总结518.零钱兑换II思路一维数组二维数组377.组合总和Ⅳ思路卡码网70.爬楼梯(进阶版)思路完全背包理论基础完全背包有N件物品和一个最多能背重量为W的背包。第i件物品的重量是weight[i],得到的价值是value[i]。每件物品都有无......