Python如何处理异常和错误?

2021年3月18日16:37:46 发表评论 626 次浏览

本文概述

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

语法错误和异常之间的区别

语法错误:顾名思义, 此错误是由代码中的错误语法引起的。它导致程序终止。

例子

# 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

例外情况:如果程序在语法上正确, 但是代码导致错误, 则会引发异常。该错误不会停止程序的执行, 但是会改变程序的正常流程。

例子:

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

输出如下:

Python异常处理2

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

注意:

Exception是Python中所有异常的基类。你可以检查异常层次结构

这里

.

尝试并在异常处理中除外

让我们尝试访问索引超出范围的数组元素并处理相应的异常。

# Python program to handle simple runtime error
  
a = [ 1 , 2 , 3 ]
try : 
     print "Second element = %d" % (a[ 1 ])
  
     # Throws error since there are only 3 elements in array
     print "Fourth element = %d" % (a[ 3 ]) 
  
except IndexError:
     print "An error occurred"

输出如下:

Second element = 2
An error occurred

一个try语句可以具有一个以上的except子句, 以指定不同异常的处理程序。请注意, 最多将执行一个处理程序。

# Program to handle multiple errors with one except statement
try : 
     a = 3
     if a < 4 :
  
         # throws ZeroDivisionError for a = 3 
         b = a / (a - 3 )
      
     # throws NameError if a >= 4
     print "Value of b = " , b
  
# note that braces () are necessary here for multiple exceptions
except (ZeroDivisionError, NameError):
     print "\nError Occurred and Handled"

输出如下:

Error Occurred and Handled

如果将" a"的值更改为大于或等于4, 则输出为

Value of b =  
Error Occurred and Handled

上面的输出是这样的, 因为python一旦尝试访问b的值, 就会发生NameError。

其他语句

在python中, 你还可以在尝试除外必须在所有except子句之后出现的block。仅当try子句未引发异常时, 代码才进入else块。

# Program to depict else clause with try-except
  
# Function which returns a/b
def AbyB(a , b):
     try :
         c = ((a + b) / (a - b))
     except ZeroDivisionError:
         print "a/b result in 0"
     else :
         print c
  
# Driver program to test above function
AbyB( 2.0 , 3.0 )
AbyB( 3.0 , 3.0 )

上面程序的输出将是:

-5.0
a/b result in 0

Python的最终关键字

Python提供了一个关键字最后, 它总是在try和except块之后执行。在try块正常终止后或由于某些异常try块终止后, finally块始终执行。

语法如下:

try:
       # Some Code.... 

except:
       # optional block
       # Handling of exception (if required)

else:
       # execute if no exception

finally:
      # Some code .....(always executed)

例子:

# Python program to demonstrate finally 
    
# No exception Exception raised in try block 
try : 
     k = 5 / / 0 # raises divide by zero exception. 
     print (k) 
    
# handles zerodivision exception     
except ZeroDivisionError:    
     print ( "Can't divide by zero" ) 
        
finally : 
     # this block is always executed  
     # regardless of exception generation. 
     print ( 'This is always executed' )

输出如下:

Can't divide by zero
This is always executed

引发异常

引发语句使程序员可以强制发生特定的异常。在raise中唯一的参数表示要引发的异常。这必须是异常实例或异常类(从Exception派生的类)。

# Program to depict Raising Exception
  
try : 
     raise NameError( "Hi there" )  # Raise Error
except NameError:
     print "An exception"
     raise  # To determine whether the exception was raised or not

上面代码的输出将简单地打印为"异常", 但由于最后一行中的raise语句, 最后也会发生运行时错误。因此, 命令行上的输出将如下所示

Traceback (most recent call last):
  File "003dff3d748c75816b7f849be98b91b8.py", line 4, in 
    raise NameError("Hi there") # Raise Error
NameError: Hi there

本文作者:

尼克·库玛·辛格(Nikhil Kumar Singh)

(nickzuck_007)

如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请发表评论。

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

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

木子山

发表评论

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