10. Errors and exceptions in Python

1. Error

  • Spelling errors , i.e. misspellings of keywords, function names or variable names; SytaxError will be prompted when keywords are misspelled, and NameError will be prompted when variable names and function names are misspelled;
  • The program does not conform to Python's syntax specifications , lacking parentheses, colons, expression errors, etc.;
  • Indentation error , generally speaking, Python is indented with 4 spaces;

2. Abnormal

Exceptions are errors thrown by a Python program while it is running. If an unhandled exception occurs in the program, the script will terminate due to the exception; only by catching these exceptions and processing them can the program not be interrupted;

  • try method to handle exception
  • Python built-in exceptions and handling
  • Rais throws exception manually
  • assert statement
  • custom exception

(1) The try method handles exceptions

The try method is used in python to handle exceptions. The basic form of the general try statement is as follows:

try:
    <语句(块)>                # 可能产生异常的语句(块)
except <异常名1>:               # 要处理的异常
    <语句(块)>                # 异常处理语句
except <异常名2>:
    <语句(块)>
else:
    <语句(块)>                # 未触发异常则执行该语句(块)
finally:                        
    <语句(块)>                # 始终执行该语句

There are two commonly used forms as follows:
Form 1:

try:
    <语句(块)>                # 可能产生异常的语句(块)
except <异常名1>:               # 要处理的异常
    <语句(块)>                # 异常处理语句

Form two:

try:
    <语句(块)>                # 可能产生异常的语句(块)
except <异常名1>:               # 要处理的异常
    <语句(块)>                # 异常处理语句
finally:                        
    <语句(块)>                # 始终执行该语句

The try method handles exception examples:

def tryFunction(n):
    lst = [1, 2, 3, 4, 5]
    try:
        a = lst[n]
    except IndexError:
        return 'Index Error'
    else:
        return a

print(tryFunction(2))
print(tryFunction(12))

Running result:
3
Index Error


(2), Python built-in exceptions and processing

In an interactive environment, use the dir(__builtins__) command to display all predefined exceptions;

Common exception definitions are shown in the following table:

exception name describe
AttributeError Calling a method that doesn't exist raises an exception
EOFError An exception raised by the silent end of the file is encountered
ImportError Exception raised by an error in importing a module
IndexError List out of bounds exception
IOError An exception raised by an I/O operation, such as an error opening a file
KeyError Exception raised with keyword that does not exist in dictionary
NameError Exception raised with non-existent variable name
TabError Exception raised by incorrect block indentation
ValueError Exception raised by search for a value that does not exist in the list
ZeroDivisionError Exception raised by division by 0

The main uses of the except statement are as follows:

  • except : catch all exceptions;
  • except<exception name> : catch the specified exception;
  • except(exception name 1, exception name 2) : catch exception 1 or exception 2;
  • except <exception name> as <data> : Capture the specified exception and its additional data;
  • except(exception name 1, exception name 2) as <data> : catch exception 1 or exception 2 and its additional data

except example:

def testExcept(index, i):
    lst = [1, 2, 3, 4, 5]
    try:
        result = lst[index] / i
    except:
        print('Error!')
    else:
        print('The Result Is', result)

testExcept(2, 2)
testExcept(2, 0)
testExcept(12, 0)

Running result:
The Result Is 1.5
Error!
Error!


(3), raise throws an exception manually

There are several ways to use raise to throw an exception:

  • raise exception name
  • raise exception name, additional data
  • raise lists

raise throws an exception example:

def testExcept(index, i):
    lst = [1, 2, 3, 4, 5]
    if len(lst) <= index:
        raise IndexError
    else:
        print('The Result Is', lst[index])
'''
    except IndexError:
        print('Index Error!')

    else:
        print('The Result Is', result)
'''

#testExcept(2, 2)
testExcept(5, 2)

Running result:
Traceback (most recent call last):
File “G:\work\python\01Python crawler base\postTest.py”, line 33, in
testExcept(5, 2)
File “G:\work\python\01Python crawler base\postTest.py", line 21, in testExcept
raise IndexError
IndexError

Example of handling raise raised manually:

def testExcept(index, i):
    lst = [1, 2, 3, 4, 5]
    try:
        if len(lst) <= index:
            raise IndexError
    except IndexError:
        print('Index Error!')
    else:
        print('The Result Is', lst[index])

testExcept(2, 2)
testExcept(5, 2)

Running result:
The Result Is 3
Index Error!


(4), assert statement

The general form of an assert statement is as follows:

assert <condition test>, <exception additional data>

  • The exception additional data is optional, when the test condition is False, an exception is thrown;
  • assert will throw an AssertionError exception;
  • Only runs when python's built-in special variable __debug__ is True

Example of assert statement:

def testAssert(i):
    try:
        assert i < 2        # 当 i >= 2时抛出异常AssertionError
    except AssertionError:
        print('Assertion Error!')
    else:
        print('i is', i)

testAssert(1)
testAssert(2)

Running result:
i is 1
Assertion Error!


(5), custom exception

  • The custom exception in Python is to inherit the Exception class
  • If you need to include certain prompt information in the exception, you can overload the __init__ and __str__ functions

Custom exception example:

class MyException(Exception):
    def __init__(self, value):
        self.value = value;
    def __str__(self):
        return self.value

raise MyException('Myself Exception!')

Running result:
Traceback (most recent call last):
File "G:\work\python\01Python crawler foundation\postTest.py", line 24, in
raise MyException('Myself Exception!')
__main__.MyException: Myself Exception!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325643211&siteId=291194637