Python programming (7)

zhaozj2021-02-08  238

Chapter VII Error and Exceptions

We have only mentioned the error message until now, and there is no detailed discussion. If you run the previous example, some error messages may have been seen. There are at least two different errors: sentence failure and exceptions.

8.1

The sentence is also known as a grammar analysis, which is the most likely mistake in learning Python.

>>> While 1 Print 'Hello World'

File "", Line 1

While 1 Print 'Hello World'

^

SyntaxError: Invalid Syntax

The grammatical analyzer repeats the wrong line and uses a small 'arrow' to point to the first place to find the wrong position. The error is caused by the previous marks in front of the arrow (at least detected here). In this example, the error detected at the keyword print because it should have a colon (":") in front. The file name and the line number are displayed in the error message. If the error occurs in a script file, you will know where to find it.

8.2 exceptions

Even if the statement or expression syntax does not have a problem, it may happen when trying to run. The error detected by run is called exception, which is not necessarily fatal: You will learn how to process exceptions in the Python program. However, most exceptions cannot be processed, this is incorrect information, such as:

>>> 10 * (1/0)

TRACEBACK (InnerMost Last):

File "", Line 1

ZerodivisionError: Integer Division or Modulo, INTEGER DIVISION or MODULO

>>> 4 SPAM * 3

TRACEBACK (InnerMost Last):

File "", Line 1

NameError: spam

>>> '2' 2

TRACEBACK (InnerMost Last):

File "", Line 1

TypeError: Illegal Argument Type for Built-in Operation

The last line of the error message shows the situation. Exceptions have different types, the type as part of the error message: The error in the above example has ZerodivisionError, NameError, and TypeError. The string displayed as an exception is an exceptional name of the exception. This is established for all built-in exceptions, but it is not necessarily established for user-defined exceptions (users best comply with this convention). The standard exception name is a built-in identifier (not a keyword).

The rest of this row is a detail of the error, which explains depending on the exception type. The part of the error message appears in the form of a stack anti-tracking display of an error. General This includes a stack reverse tracking of a list of source line rows listed in the source code row; however, it does not display rows that are read from the standard input.

The library reference manual lists the built-in exceptions and its meaning.

8.3 exception processing

The selected exception can be programmed. Please see the example below, display some reciprome of floating point numbers:

>>> NUMBERS = [0.3333, 2.5, 0, 10]

>>> for x in numbers:

... Print X,

... TRY:

... Print 1.0 / x

... Except ZerodiVisionError:

... Print '*** Has no inverse ***' ...

0.3333 3.00030003

2.5 0.4

0 *** HAS no inverse ***

10 0.1

The TRY statement is working this:

First, run the TRY clause (between the statement between TRY and Except). If there is no exception, skip the Except clause, the TRY statement is running. If an exception error has occurred in the Try clause and exception error matches the exception name specified after ExcePT, skip the remaining part of the TRY clause, execute the Except clause, and continue the program later behind the TRY statement. If an exception error occurs in the Try clause, the exception name specified after exception is not matched, the exception is transmitted to the outer layer TRY sentence. If this exception is not found, this exception is called unprocessed exception, the program stops running, and the error message is displayed.

The TRY sentence can have multiple Except clauses, specify different processing for different exceptions. Only one error handler is only executed. The error handler only processes the exceptions that occur in the corresponding TRY clause, if the exception error handler does not respond to other error handles in the TRY sentence. An Except clause can list more exceptions, write in parentheses with commas, for example:

... ExcePt (RuntimeError, TypeError, NameError):

... Pass

The last Except clause can omit the extrovable appearance as a communication. This approach should be used with caution, as this may lead to the actual error, but I can't find it.

The Try ... Except statement has an optional else clause, and if you have to put it behind all Except clauses. Else does not have exceptions, we can put things that must be done in this clause in this clause in the trory clause. E.g:

For arg in sys.argv [1:]:

TRY:

f = Open (arg, 'r')

Except Ioerror:

Print 'can't open', arg

Else:

Print Arg, 'has', len (f.readlines ()),' row

f.close ()

Exceptional occurs when there is a value, called exceptional parameters. Whether the parameter exists and its type depend on the type of exception. For exceptions with parameters, Except can specify a variable in an exception name (or table) at home, such as:

>>> TRY:

... spam ()

... Except NameError, x:

... Print 'Name', X, 'undefined'

...

Name spam underefined

The parameter value is listed at the last details section of the error message when there is an exception to the parameter.

The exception handler not only processes the exceptions directly in the TRY clause, but also the exceptions in the function (even indirect call functions) called in the TRY clause. Such as:

>>> DEF this_fails ():

... x = 1/0

...

>>> TRY:

... this_fails ()

... Except ZerodiVisionerror, Detail:

... Print 'Handling Run-Time Error:', Detail

...

Handling Run-Time Error: Integer Division or MODULO

8.4 generation exception

The RAISE statement allows programmers to force generation to generate specified exceptions. For example: >>> Raise NameError, 'Hithere'

TRACEBACK (InnerMost Last):

File "", Line 1

Namerror: Hithere

The first parameter of the RAISE statement specifies the name of the exception to be generated. An optional second parameter specifies the exceptional parameter.

8.5 User Custom Exceptions

You can define your own exception in the program, just assign a character to a variable. E.g:

>>> MY_EXC = 'my_exc'

>>> TRY:

... raise my_exc, 2 * 2

... EXCEPT MY_EXC, VAL:

... Print 'My Exception Occurred, Value:', VAL

...

MY Exception Occurred, Value: 4

>>> RAISE MY_EXC, 1

TRACEBACK (InnerMost Last):

File "", Line 1

MY_EXC: 1

Many standard modules use this method to report the errors that have occurred in their defined functions.

8.6 Defining Cleaning Action

The TRY statement has another Finally optional clause that can be used to specify the action that must be performed regardless of the error or not. E.g:

>>> TRY:

... Raise KeyboardInterrupt

... Finally:

... Print 'Goodbye, World!'

...

Goodbye, World!

TRACEBACK (InnerMost Last):

File "", Line 2

KeyBoardInterrupt

The Finally clause will be executed regardless of whether an exception occurred in the TRY clause. When an exception occurs, first execute the finally clause and re-raise this exception. The finally clause will also be executed when the TRY statement exits with a BREK or RETURN statement.

It is to be noted that the TRY statement has an Except clause to have a finally clause. If you have a Finally clause, you can't have an Except clause, you can't use the Except clause and the Finally clause. You can nest.

转载请注明原文地址:https://www.9cbs.com/read-2233.html

New Post(0)