Python|python基础:不能忽视的错误和异常

Python|python基础:不能忽视的错误和异常

文章图片

Python|python基础:不能忽视的错误和异常

文章图片

Python|python基础:不能忽视的错误和异常

错误是程序中的问题 , 由于该程序将停止执行 。 另一方面 , 当发生一些内部事件 , 更改程序的正常流时 , 将引发异常 。
语法错误当未遵循语言的正确语法时 , 将引发语法错误 。
例子:
# initialize the amount variableamount= 10000# check that You are eligible to#  purchase Dsa Self Paced or notif(amount>2999)print(\"You are eligible to purchase Dsa Self Paced\")输出:
它返回语法错误消息 , 因为 if 语句缺少冒号之后 。 我们可以通过编写正确的语法来解决这个问题 。
逻辑错误(异常)在运行时发生错误后通过语法测试称为异常或逻辑类型 。 例如 , 当我们将任何数字除以零时 , 将引发异常 , 或者当我们导入不存在的模块时 , 将引发异常 。
示例 1:当我们尝试将数字除以 0 时 , 零分视器可能 。
# initialize the amount variablemarks= 10000 # perform division with 0a= marks/ 0print(a)输出:

示例 2:当缩进不正确时
if(a<3):print(\"gfg\")输出:

还存在一些常见的内置异常:


 错误处理【Python|python基础:不能忽视的错误和异常】当引发错误和异常时 , 我们借助 Handle 方法处理该错误和异常 。

  • 使用 Try/例外/最后
    我们可以通过 Try/例外/最后方法处理异常 。
例子:
# put unsafe operation in try blocktry:print(\"code start\") # unsafe operation performprint(1 / 0) # if error occur the it goes in except blockexcept:print(\"an error occurs\") # final code in finally blockfinally:print(\"GeeksForGeeks\")输出:
code start
an error occurs
GeeksForGeeks
对预定义条件引发异常当
我们想要为某些条件的限制编写代码时 , 我们可以引发异常 。

示例:
# try for unsafe codetry:amount= 1999if amount <2999: # raise the ValueErrorraise ValueError(\"please add money in your account\")else:print(\"You are eligible to purchase DSA Self Paced course\") # if false then raise the value errorexcept ValueError as e:print(e)输出:
please add money in your account


    推荐阅读