Figure python | error and exception handling

Author: Han Xinzi@ShowMeAI
Tutorial address: http://www.showmeai.tech/tuto...
Article address: http://www.showmeai.tech/article-detail/87
Notice: All Rights Reserved. Please contact the platform and the author for reprint and indicate the source

1. Python 3 errors and exceptions

In the actual programming process, we often see some error messages, and there are special ways to deal with errors and exceptions in python to ensure the smooth global process.

Syntax errors and exceptions in Python are easy to identify. We can also use try Except to do the corresponding processing.

2. Syntax error

Beginners often encounter Python syntax errors or parsing errors, as shown in the following real code example

>>> while True print('Hello ShowMeAI')
  File "<stdin>", line 1, in ?
    while True print('Hello ShowMeAI')
                   ^
SyntaxError: invalid syntax

In this example, the function print() is checked for an error, and a colon is missing in front of it:.

The parser points out the wrong line and marks a small arrow where the first error is found.

3. Abnormal

Even if the syntax of a Python program is correct, errors may occur when running it. Errors detected during runtime are called exceptions.

Most exceptions are not handled by the program and are displayed here in the form of error messages (the following code can be found in Online Python 3 environment Running in:

for i in range(5,-5,-1):
    print(5/i)

The results are as follows:

1.0
1.25
1.6666666666666667
2.5
5.0
Traceback (most recent call last):
  File "<string>", line 4, in <module>
ZeroDivisionError: division by zero

Exceptions appear in different types, which are printed as part of the information: the types in the example are ZeroDivisionError, NameError and TypeError.

The front part of the error message shows the context in which the exception occurred, and displays the specific information in the form of call stack.

4. Exception handling

(1)try-except

Exception capture can use the try/except statement.

In the following example, let the user enter a legal integer, but allow the user to interrupt the program (using Control-C or the method provided by the operating system). The message of user interruption will throw a KeyboardInterrupt exception.

while True:
    try:
        x = int(input("Please enter a number: "))
        break
    except ValueError:
        print("The number you entered is not a number, please try again!")

The try statement works as follows:;

  • First, execute the try clause (the statement between the keyword try and the keyword except).
  • If no exception occurs, the exception clause is ignored and the try clause ends after execution.
  • If an exception occurs during the execution of the try clause, the rest of the try clause is ignored. If the type of exception matches the name after exception, the corresponding exception clause will be executed.
  • If an exception does not match any except, the exception will be passed to the upper try.

The exception clause contains a specific exception, which may be handled by one or more branches.

The handler will only handle exceptions in the corresponding try clause, not exceptions in other try handlers.

An exception clause can handle multiple exceptions at the same time. These exceptions will be placed in a bracket as a tuple, for example:

except (RuntimeError, TypeError, NameError):
    pass

The last exception clause can ignore the name of the exception, which will be used as a wildcard. You can use this method to print an error message and then throw the exception again.

import sys

try:
    f = open('ShowMeAI.txt')
    s = f.readline()
    i = int(s.strip())
except OSError as err:
    print("System error: {0}".format(err))
except ValueError:
    print("Cannot convert to integer")
except:
    print("unknown error:", sys.exc_info()[0])
    raise

(2)try-except-else

The try/except statement also has an optional else clause. If this clause is used, it must be placed after all except clauses.

The else clause will be executed when no exception occurs in the try clause.

The following examples judge whether the file can be opened in the try statement. If there is no exception when opening the file, execute the else part of the statement to read the file content:

for arg in sys.argv[1:]:
    try:
        f = open(arg, 'r')
    except IOError:
        print('could not open file', arg)
    else:
        print(arg, 'have', len(f.readlines()), 'that 's ok')
        f.close()

Using else clause is better than putting all statements in try clause, which can avoid some unexpected exceptions that can not be caught by except.

Exception handling does not only deal with exceptions that happen directly in the try clause, but also handles exceptions thrown in functions that are called in the clause (or even indirectly called functions). For example:

>>> def this_fails():
        x = 1/0
   
>>> try:
        this_fails()
    except ZeroDivisionError as err:
        print('An error occurred:', err)

#An error occurred: int division or module by zero

(3) Try finally statement

The try finally statement executes the last code regardless of whether an exception occurs.

In the following examples, the finally statement will be executed regardless of whether an exception occurs:

try:
    runoob()
except AssertionError as error:
    print(error)
else:
    try:
        with open('ShowMeAI.log') as file:
            read_data = file.read()
    except FileNotFoundError as fnf_error:
        print(fnf_error)
finally:
    print('This sentence is executed whether or not an exception occurs.')

5. Throw an exception

Python uses the raise statement to throw a specified exception.

The format of raise syntax is as follows:

raise [Exception [, args [, traceback]]]

The following example code triggers an exception if x is greater than 10:

x = 20
if x > 10:
    raise Exception('x Cannot be greater than 10. x The value of is: {}'.format(x))

Executing the above code will trigger an exception:

Traceback (most recent call last):
  File "test.py", line 3, in <module>
    raise Exception('x Cannot be greater than 5. x The value of is: {}'.format(x))
Exception: x Cannot be greater than 10. x The value of is: 20

The only argument to raise specifies the Exception to be thrown. It must be an instance of an Exception or an Exception class (that is, a subclass of Exception).

If you just want to know if this throws an exception and don't want to deal with it, a simple raise statement can throw it again.

>>> try:
        raise NameError('NewError')
    except NameError:
        print('An exception!')
        raise
   
An exception!
Traceback (most recent call last):
  File "<stdin>", line 2, in ?
NameError: NewError

6. User defined exception

You can have your own exceptions by creating a new Exception class. The Exception class inherits from the Exception class and can be inherited directly or indirectly, for example:

>>> class NewError(Exception):
        def __init__(self, value):
            self.value = value
        def __str__(self):
            return repr(self.value)
   
>>> try:
        raise NewError(2*2)
    except NewError as e:
        print('New exception occurred, value:', e.value)
   
My exception occurred, value: 4
>>> raise NewError('oops!')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
__main__.NewError: 'oops!'

In this example, the class Exception is the default__ init__ () is covered.

When creating a module may throw many different exceptions, a common approach is to create a basic exception class for the package, and then create different subclasses for different error conditions based on this basic class:

class Error(Exception):
    """Base class for exceptions in this module."""
    pass

class InputError(Error):
    """Exception raised for errors in the input.

    Attributes:
        expression -- input expression in which the error occurred
        message -- explanation of the error
    """

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

class TransitionError(Error):
    """Raised when an operation attempts a state transition that's not
    allowed.

    Attributes:
        previous -- state at beginning of transition
        next -- attempted new state
        message -- explanation of why the specific transition is not allowed
    """

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

Most exception names end with "Error", just like standard exception names.

7. Define cleanup behavior

The try statement has another optional clause that defines the cleanup behavior that will be performed in any case. For example:

>>> try:
...     raise KeyboardInterrupt
... finally:
...     print('Goodbye, ShowMeAI!')
...
Goodbye, ShowMeAI!
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
KeyboardInterrupt

In the above example, the finally clause will be executed regardless of whether there is an exception in the try clause.

If an exception is thrown in the try clause (or in the except and else clauses) and no exception intercepts it, the exception will be thrown after the finally clause is executed.

The following is a more complex example (except and finally clauses are included in the same try statement):

>>> def divide(x, y):
        try:
            result = x / y
        except ZeroDivisionError:
            print("Divisor is 0!")
        else:
            print("The result is", result)
        finally:
            print("End of division calculation")
   
>>> divide(2, 1)
The result is 2.0
 End of division calculation
>>> divide(2, 0)
Divisor is 0!
End of division calculation
>>> divide("2", "1")
End of division calculation
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 3, in divide
TypeError: unsupported operand type(s) for /: 'str' and 'str'

8. Predefined cleanup behavior

Some objects define standard cleanup behavior. No matter whether the system successfully uses it or not, once it is no longer needed, the standard cleanup behavior will be executed.

This example shows trying to open a file and then print the content to the screen:

for line in open("ShowMeAI.txt"):
    print(line, end="")

The problem with the above code is that after execution, the file will remain open and not closed.

The keyword with statement can ensure that objects such as files will correctly execute their cleaning methods after use:

with open("ShowMeAI.txt") as f:
    for line in f:
        print(line, end="")

After the above code is executed, even if there is a problem in the processing process, the file f will always be closed.

9. Video tutorial

Please click to station B to view the version of [bilingual subtitles]

https://www.bilibili.com/vide...

Data and code download

The code for this tutorial series can be found in github corresponding to ShowMeAI Download in, you can run in the local python environment. Babies who can surf the Internet scientifically can also directly use Google lab to run and learn through interactive operation!

The Python quick look-up table involved in this tutorial series can be downloaded and obtained at the following address:

Extended references

ShowMeAI related articles recommended

ShowMeAI series tutorial recommendations

Keywords: Python Programming Machine Learning AI

Added by jimmyhumbled on Wed, 23 Feb 2022 11:06:36 +0200