Make use of exception handling (try-except)

introduce

Briefly introduce Python's exception handling (try-except).

basic grammar

Try-except is the basis of exception handling in Python.

As an example, we will explain the situation when a ZeroDivisionError occurs when performing division by zero.
When dividing by zero, the following error occurs.

print(1 / 0)
# ZeroDivisionError: division by zero

To catch this exception, write as follows.

try:
    print(1 / 0)
except ZeroDivisionError:
    print('Error')
# Error

iftryAn error occurred with exception name in clause,except exception namewill be interruptedtryclause and executeexceptcode in the clause.
Additionally, by using except exception name as variable name, exception objects can be stored and used in variables. The exception object stores the error message and you can view the details of the error.

try:
    print(1 / 0)
except ZeroDivisionError as e:
    print(e)
    print(type(e))
# division by zero
# <class 'ZeroDivisionError'>

You can also capture by specifying a base class. For example,ZeroDivisionErrorThe base class isArithmeticError. This variable stores the actual derived class exception object that occurred.

try:
    print(1 / 0)
except ArithmeticError as e:
    print(e)
    print(type(e))
# division by zero
# <class 'ZeroDivisionError'>

Handle multiple exceptions differently

If you want to catch multiple exceptions and handle them differently, set except for each exception.

def divide(a, b):
    try:
        print(a / b)
    except ZeroDivisionError as e:
        print('catch ZeroDivisionError:', e)
    except TypeError as e:
        print('catch TypeError:', e)

divide(1, 0)
# catch ZeroDivisionError: division by zero

divide('a', 'b')
# catch TypeError: unsupported operand type(s) for /: 'str' and 'str'

Perform the same operation on multiple exceptions

Multiple exceptions can be caught using a single except clause by specifying the exception name in a tuple.

def divide(a, b):
    try:
        print(a / b)
    except (ZeroDivisionError, TypeError) as e:
        print(e)

divide(1, 0)
# division by zero

divide('a', 'b')
# unsupported operand type(s) for /: 'str' and 'str'

Catch all exceptions and perform the same handling

If you want to catch all exceptions, you can write without specifying the exception name.

try:
    print(1 / 0)
except:
    print('Error')
# Error

If there are multipleexceptclause, then only in the lastexceptOmit the exception name from the clause. (likeifin the sentenceElifandelseSame)

Normal end processing: else

can be specified intryclause ends andelseThe processing to be performed if no exception occurs in the clause.

def divide(a, b):
    try:
        print(a / b)
    except ZeroDivisionError as e:
        print('catch ZeroDivisionError:', e)
    else:
        print('finish (no error)')

divide(1, 2)
# 0.5
# finish (no error)

divide(1, 0)
# catch ZeroDivisionError: division by zero

Processing is always executed on termination: finally

You can specify in the finally clause a procedure that is always executed last, regardless of whether an exception occurs.

def divide(a, b):
    try:
        print(a / b)
    except ZeroDivisionError as e:
        print('catch ZeroDivisionError:', e)
    finally:
        print('all finish')

divide(1, 2)
# 0.5
# all finish

divide(1, 0)
# catch ZeroDivisionError: division by zero
# all finish

generalize

  • except exception name: catch specific exceptions
  • except exception name as variable name: store the exception object in a variable
  • except can set multiple exceptions.
  • If no exception name is specified in except, all exceptions are caught.
try:
    print(1 / 0)
except: # 如果try中出现异常
    print('Error')
else: # 如果try中没有出现异常
    print('finish (no error)')
finally: # 无论异常如何发生,始终执行
    print('all finish')

Guess you like

Origin blog.csdn.net/Allan_lam/article/details/134931949