Python 3 quick start tutorial errors and exceptions

Posted by bigger on Thu, 07 May 2020 10:12:10 +0200

There are at least two types of errors in Python: syntax errors and exceptions.

syntax error

Syntax errors are also called parsing errors:

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

The parser indicates the error line and displays ^ before the location where the error was detected.

abnormal

Even if a statement or expression is syntactically correct, it can cause errors when executed. Errors detected during runtime are called exceptions

What I don't know in the learning process can add to me
python Learning buckle qun,784758214
//There are good practical courses, development tools and e-books in the group
//Share with you the current talent needs of python enterprises and how to learn python from scratch, and what to learn

>>> 10 * (1/0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly

The last line of the error message indicates what error occurred. There are also different types of exceptions, which are displayed as part of the error message: the exceptions in the example are ZeroDivisionError, NameError and TypeError. When printing error information, the type of exception is displayed as the built-in name of the exception. This is true for all built-in exceptions, but user-defined exceptions are not necessarily (although this is a useful Convention). Standard exception names are built-in identifiers (non reserved keywords).

The latter part of the line is a detailed description of the exception type, which means that its content depends on the exception type.

The first half of the error message lists where the exception occurred in the form of a stack. The source lines are usually listed in the stack, however, the source code from standard input is not displayed.

Built in exceptions list built-in exceptions and what they mean.

exception handling

Example: the user is required to enter a valid integer, but is allowed to interrupt the program (using Control-C or any method supported by the system). Note: user generated interrupts cause KeyboardInterrupt exceptions.


>>> while True:
...     try:
...         x = int(input("Please enter a number: "))
...         break
...     except ValueError:
...         print("Oops!  That was no valid number.  Try again...")

The try statement works as follows.

  • First, execute the content between try and except
  • If no exception occurs, ignore the except statement.
  • If an exception occurs during the execution of a try clause, the rest of the clause is ignored. If the exception matches the exception type specified after *, the corresponding exception clause is executed. Then continue to execute the code after the try statement.
  • If an exception occurs and there is no matching branch in the exception clause, it is passed to the previous try statement. If the corresponding processing statement cannot be found, it will become an unhandled exception, terminate the program operation, and display a prompt message.

A try statement may contain more than one except clause, which specifies that different exceptions are handled. Take at most one branch. The exception handler will only handle the exceptions in the corresponding try clause. In the same try statement, the exceptions in other clauses will not be handled. The exception clause can list the names of multiple exceptions in a tuple, for example:

... except (RuntimeError, TypeError, NameError):
... pass

Exception matching: if the class in the except ion clause is the same class or its base class (otherwise, if it is a subclass, it is not allowed). For example, the following code prints B, C, D in this order:

class B(Exception):
    pass

class C(B):
    pass

class D(C):
    pass

for cls in [B, C, D]:
    try:
        raise cls()
    except D:
        print("D")
    except C:
        print("C")
    except B:
        print("B")

If except B is earlier, B, B, B will be printed.

Finally, the exception clause can omit the exception name as a wildcard. Please use this function carefully, because it is easy to cover up real programming errors! It can also be used to print error messages and then re throw the exception (which also allows the caller to handle the exception):

import sys

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except OSError as err:
    print("OS error: {0}".format(err))
except ValueError:
    print("Could not convert data to an integer.")
except:
    print("Unexpected error:", sys.exc_info()[0])
    raise

try … An except statement can have an else clause, which can only appear after all except clauses. When the try statement does not throw an exception, you need to execute some code. You can use this clause. For example:


for arg in sys.argv[1:]:
    try:
        f = open(arg, 'r')
    except OSError:
        print('cannot open', arg)
    else:
        print(arg, 'has', len(f.readlines()), 'lines')
        f.close()

Using else clause is better than appending code in try clause, because it can avoid try Exception unexpectedly intercepts except ions thrown by code that does not belong to them.

When an exception occurs, there may be related values that exist as parameters of the exception. Whether this parameter exists and what type it is depends on the type of exception.

After the exception name (tuple), you can also specify a variable for the exception clause. This variable is bound to the exception instance and is stored in the instance.args parameter. For convenience, the exception instance defines str(), so that you can directly access the print parameters without having to reference. Args. You can also initialize an exception before throwing it and add properties to it as needed.

What I don't know in the learning process
 python learning buckle qun, 784758214
 There are good practical courses, development tools and e-books in the group
 Share with you the current talent needs of python enterprises and how to learn python from scratch, and what to learn
>>> try:
...     raise Exception('spam', 'eggs')
... except Exception as inst:
...     print(type(inst))    # the exception instance
...     print(inst.args)     # arguments stored in .args
...     print(inst)          # __str__ allows args to be printed directly,
...                          # but may be overridden in exception subclasses
...     x, y = inst.args     # unpack args
...     print('x =', x)
...     print('y =', y)
...
<class 'Exception'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs

For unhandled exceptions, if they have parameters, they are printed as the last part of the exception information ("details").

Exception handlers not only handle exceptions that happen immediately in the try clause, but also handle the exceptions that occur inside the functions that are called in the try clause. For example:


>>> try:
...     raise Exception('spam', 'eggs')
... except Exception as inst:
...     print(type(inst))    # the exception instance
...     print(inst.args)     # arguments stored in .args
...     print(inst)          # __str__ allows args to be printed directly,
...                          # but may be overridden in exception subclasses
...     x, y = inst.args     # unpack args
...     print('x =', x)
...     print('y =', y)
...
<class 'Exception'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs

Throw exception

The raise statement can force the specified exception to be thrown. For example:


>>> raise NameError('HiThere')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: HiThere

The Exception to be thrown is identified by the unique parameter of raise. It must be an Exception instance or Exception class (a class inherited from Exception). If an Exception class is passed, it is implicitly instantiated by calling its parameterless constructor:


raise ValueError  # shorthand for 'raise ValueError()'

If you want to know whether an exception is thrown, but you don't want to handle it, the raise statement can simply rethrow the exception:

>>> try:
...     raise NameError('HiThere')
... except NameError:
...     print('An exception flew by!')
...     raise
...
An exception flew by!
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
NameError: HiThere

User defined exception

Inherited exceptions directly or indirectly can be customized.

The exception class can define anything that can be defined in any other class, but usually in order to keep it simple, only a few attribute information is added to it for exception handling handle extraction. If several different errors need to be thrown in the newly created module, it is usually done to define the exception base class for the module, and then derive the corresponding exception subclass according to different error types:


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

Similar to standard exceptions, most exceptions are named after "Error.".

Many standard modules define their own exceptions to report errors that may occur in the functions they define. For more information about Classes, see Classes.

Define cleanup behavior

The try statement has optional clauses that define the cleanup operations that must be performed in any case. For example:


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

Whether or not an exception occurs, the finally clause is executed before the program leaves try. When an uncaught exception occurs in a statement (or it occurs in an exception or else clause), it is thrown again after the finally clause is executed. A try statement exit through a break, continue, or return statement also executes a finally clause.


>>> def divide(x, y):
...     try:
...         result = x / y
...     except ZeroDivisionError:
...         print("division by zero!")
...     else:
...         print("result is", result)
...     finally:
...         print("executing finally clause")
...
>>> divide(2, 1)
result is 2.0
executing finally clause
>>> divide(2, 0)
division by zero!
executing finally clause
>>> divide("2", "1")
executing finally clause
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in divide
TypeError: unsupported operand type(s) for /: 'str' and 'str'

finally clauses are often used to release external resources (such as files or network connections).

Predefined cleanup behavior

Some objects define standard cleanup behavior, which will work when they are no longer needed, regardless of whether the object operation is successful or not. The following example attempts to open a file and output the contents to the screen.

What I don't know in the learning process can add to me
 python learning buckle qun, 784758214
 There are good practical courses, development tools and e-books in the group
 Share with you the current talent needs of python enterprises and how to learn python from scratch, and what to learn

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

The problem with this code is that the open file is not closed immediately after code execution. There's nothing in a simple script, but large applications can go wrong. With statement enables objects such as files to be cleaned up timely and accurately.

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

After the statement is executed, the file f is always closed, even if there is an error processing the file line. Whether other objects provide predefined cleanup behaviors should refer to relevant documents.

Topics: Programming Python REST Attribute