current position:Home>Python notes (22): errors and exceptions

Python notes (22): errors and exceptions

2022-01-30 16:49:49 A bowl week

Little knowledge , Great challenge ! This article is participating in “ A programmer must have a little knowledge ” Creative activities .

Hello everyone , I am a A bowl week , One doesn't want to be drunk ( Internal volume ) The front end of the . If you are lucky enough to get your favor , I'm very lucky ~

In daily learning Python In the process , Due to its limited programming level , It really hurts me to throw an exception to me from time to time ; Found in the process of learning Python Errors in can be divided into syntax errors and exceptions .

Grammar mistakes

Python Grammatical errors in are usually the most obvious errors , Because the code is not written as required , It is often prone to grammatical errors

Sample code

>>> print("hello world)
  File "<stdin>", line 1
    print("hello world)
                      ^
SyntaxError: EOL while scanning string literal
>>> while True print("hello world")
  File "<stdin>", line 1
    while True print("hello world")
                   ^
SyntaxError: invalid syntax
 Copy code 

Python The syntax interpreter will find out where the error occurs first , And mark a small arrow below it

abnormal

What is an anomaly ? An exception is an event , This event will occur while the program is running , Affect the normal execution of the program ; because Python in Everything is object , So the exception is also an object , It means an error ; In general, even if Python The grammar is correct , When it's running , There is also the possibility of mistakes , Errors detected during runtime are called exceptions .

Example

>>> print(1 / 0)   # 0  Not as a divisor , An exception 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>> print(my_name)  # # my_name  Undefined , An exception 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'my_name' is not defined
>>> print("5" + 5)  # # int  Cannot be associated with  str  Add up , An exception 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
 Copy code 

Different exceptions will prompt different error messages , The first part of the error message shows the context in which the exception occurred , And display the specific information in the form of call stack .

At the end of the article, all the common error messages are sorted out Portal

exception handling

When Python When an exception occurs in the script, we don't catch and handle it in time , The program will terminate execution .python Use in try/except Statement can handle exceptions well .

Sample code

try:
    print(my_name)  #  No definition my_nama Variable , An exception will occur 
    print(" I am the result of normal execution ")  #  If the program is normal, it will execute this code 
except NameError:
    print(" If something unusual happens , Will execute me ")  #  If an error occurs, this code will be executed 
 Copy code 

Execute the process :

  1. Executive execution try Clause ( In keywords try And keywords except The sentence between )
  2. Variable not found , trigger NameError error
  3. The exception type is exactly the same as except The following statements are consistent with , Ought to be except Clause will be executed

Be careful : If the exception does not match it , Still throw exceptions

If you want one except Clause can handle multiple exceptions at the same time , These exceptions will be placed in parentheses as a tuple , for example :

try:
    pass
except (RuntimeError, TypeError, NameError):
    pass
 Copy code 

One try A statement can also contain multiple except Clause , To handle different specific exceptions . At most one branch will be executed .

the last one except Clause to ignore the name of the exception , It will be used as a wildcard . Can pass raise Throw an exception

Sample code

while True:
    try:
        a = int(input(" Please enter the dividend :"))
        b = int(input(" Please enter the dividend :"))
        c = a / b
        print(" The result is :", c)
        break  #  Out of the loop 
    except ValueError:
        print(" The input is not a number , Please re-enter ")
    except:
        print(" Unknown exception ")
        raise  #  If not ValueError, Will print the previous statement and throw an exception 
 Copy code 

Execute the process

try/except...else

try/except There is also an optional else Clause , Want to use this clause , It must be placed in all except After Clause .

else Clause will be try Clause is executed when no exception occurs .

Execute the process

Sample code :

while True:
    try:
        a = int(input(" Please enter the dividend :"))
        b = int(input(" Please enter the dividend :"))
    except ValueError:
        print(" The input is not a number , Please re-enter ")
    except ZeroDivisionError:
        print(" The divisor is 0")
    else:
        c = a / b
        print(" The result is :", c)
        print(' Calculation completed ')
        break
 Copy code 

There is a small problem here , If in an endless loop statement ,try There is break keyword , They don't execute else sentence

Use else Clause is better than putting all statements in try The clause is better , This can avoid some unexpected , and except An exception that can't be caught .

try-finally sentence

try-finally Statement will execute the last code whether or not an exception occurs .

while True:
    try:
        a = int(input(" Please enter the dividend :"))
        b = int(input(" Please enter the dividend :"))
    except ValueError:
        print(" The input is not a number , Please re-enter ")
    except ZeroDivisionError:
        print(" The divisor is 0")
    else:
        c = a / b
        print(" The result is :", c)
        print(' Calculation completed ')
        break
    finally:
        print(" The program is finished ")  #  this sentence , Whether or not an exception occurs, it will execute 
 Copy code 

Throw an exception

Python Use raise Statement throws a specified exception

Grammatical structure

raise [Exception [, args [, traceback]]]
 Copy code 

Exception It's the type of exception ( for example ,NameError) Any of the parameter standard exceptions

args It is an exception parameter provided by itself ( Optional ).

tracebackargs It's tracking exception objects ( Optional ).

Sample code

x = int(input())  #  Get a number 
if x == 0:
    #  If it is equal to 0 Throw out Exception abnormal  
    raise Exception('x be equal to 0.')  # Exception: x be equal to 0.
 Copy code 

The previous code has a bug, The divisor is 0 Throw an exception directly , A solution in this way

while True:
    try:
        a = int(input(" Please enter the dividend :"))
        b = int(input(" Please enter the dividend :"))
        if b == 0:
            raise ZeroDivisionError(' The divisor is equal to 0.')
    except ValueError as e:  #  Pass exception information to e
        print(e)  #  Print out the exception information 
        print(" The input is not a number , Please re-enter ")
    except ZeroDivisionError:
        print(" The divisor is 0")
    else:
        c = a / b
        print(" The result is :", c)
        print(' Calculation completed ')
        break
    finally:
        print(" The program is finished ")  #  this sentence , Whether or not an exception occurs, it will execute 
 Copy code 

dxcept...as... You can pass exception information

User defined exception

You can have your own exceptions by creating a new exception class . Exception classes inherit from Exception class , Can inherit directly , Or indirectly

Sample code

#  Customize an exception class 
class MyError(Exception):  #  Exception classes inherit from  Exception  class 
    """
     An exception class defined by yourself 
    """

    def __init__(self, message):
        self.message = message


raise MyError(" An exception class defined by yourself ")
 Copy code 

copyright notice
author[A bowl week],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201301649472109.html

Random recommended