Python中的错误和异常详细解读

2021年3月12日14:06:51 发表评论 672 次浏览

本文概述

错误是程序中的问题, 由于这些问题而导致程序停止执行。另一方面, 当某些内部事件发生时, 会引发异常, 从而改变程序的正常流程。

python中会发生两种类型的错误。

  1. 语法错误
  2. 逻辑错误(异常)

语法错误

如果未遵循正确的语言语法, 则会引发语法错误。

例子

# initialize the amount variable
amount = 10000
  
# check that You are eligible to
#  purchase Dsa Self Paced or not
if (amount> 2999 )
     print ( "You are eligible to purchase Dsa Self Paced" )

输出如下:

Python中的错误和异常1

它返回语法错误消息, 因为在if语句后加冒号:不见了。我们可以通过编写正确的语法来解决此问题。

逻辑错误(异常)

在运行时中, 通过语法测试后发生错误的情况称为异常或逻辑类型。例如, 当我们将任何数字除以零时, ZeroDivisionError引发异常, 或者当我们导入不存在的模块时ImportError被提出。

范例1:

# initialize the amount variable
marks = 10000
  
# perform division with 0
a = marks / 0
print (a)

输出如下:

Python中的错误和异常2

在上面的示例中, 我们尝试将数字除以0时出现ZeroDivisionError。

范例2:缩进不正确时。

if (a< 3 ):
print ( "gfg" )

输出如下:

Python中的错误和异常3

除上述异常外, 一些常见的内置异常是:

例外 描述
IndexError 当检索到错误的列表索引时。
断言错误 当断言语句失败时发生
AttributeError 当属性分配失败时, 会发生这种情况。
ImportError 当找不到导入的模块时发生。
KeyError 当找不到字典的键时会发生。
NameError 未定义变量时发生。
MemoryError 当程序内存不足时会发生这种情况。
TypeError 当以错误的类型应用功能和操作时, 会发生这种情况。

注意:有关更多信息, 请参阅Python中的内置异常

错误处理

当出现错误和异常时, 我们将借助Handling方法进行处理。

使用Try / Except / Finally处理异常

我们可以通过Try / Except / Finally方法处理错误。我们在try中编写不安全的代码, 在except中回退代码, 在finally块中返回最终代码。

例子

# put unsafe operation in try block
try :
      print ( "code start" )
          
      # unsafe operation perform
      print ( 1 / 0 )
  
# if error occur the it goes in except block
except :
      print ( "an error occurs" )
  
# final code in finally block
finally :
      print ( "lsbin" )

输出如下:

code start
an error occurs
lsbin

为预定义条件引发异常

当我们想为某些条件的限制进行编码时, 我们可以引发一个异常。

例子

# try for unsafe code
try :
     amount = 1999
     if amount < 2999 :
          
         # raise the ValueError
         raise ValueError( "please add money in your account" )
     else :
         print ( "You are eligible to purchase DSA Self Paced course" )
              
# if false then raise the value error
except ValueError as e:
         print (e)

输出如下:

please add money in your account

注意怪胎!巩固你的基础Python编程基础课程和学习基础知识。

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: