📜  Python中的错误和异常

📅  最后修改于: 2022-05-13 01:55:18.864000             🧑  作者: Mango

Python中的错误和异常

错误是程序中的问题,由于该问题程序将停止执行。另一方面,当一些内部事件发生改变程序的正常流程时,就会引发异常。
Python中出现两种类型的错误。

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

语法错误

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

Python3
# 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")


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


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


Python3
# 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("GeeksForGeeks")


Python3
# 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)


输出:

它返回语法错误消息,因为在 if 语句之后缺少冒号:。我们可以通过编写正确的语法来解决这个问题。

逻辑错误(异常)

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

Python3

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

输出:

在上面的例子中,ZeroDivisionError 因为我们试图将一个数字除以 0。
示例 2:当缩进不正确时。

Python3

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

输出:

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

ExceptionDescription
IndexErrorWhen the wrong index of a list is retrieved.
AssertionErrorIt occurs when the assert statement fails
AttributeErrorIt occurs when an attribute assignment is failed.
ImportErrorIt occurs when an imported module is not found.
KeyErrorIt occurs when the key of the dictionary is not found.
NameErrorIt occurs when the variable is not defined.
MemoryErrorIt occurs when a program runs out of memory.
TypeErrorIt occurs when a function and operation are applied in an incorrect type.

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

错误处理

当引发错误和异常时,我们会在处理方法的帮助下进行处理。

  • 使用 Try/Except/Finally 处理异常
    我们可以通过 Try/Except/Finally 方法来处理错误。我们在 try 中编写了不安全的代码,在 except 中编写了回退代码,在 finally 块中编写了最终代码。
    例子

Python3

# 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("GeeksForGeeks")
  • 输出:
code start
an error occurs
GeeksForGeeks
  • 为预定义条件引发异常
    当我们想为某些条件的限制编写代码时,我们可以引发异常。
    例子

Python3

# 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