Python 3 Quick Start Tutorial Errors and Exceptions
Python 3 Quick Start Tutorial Errors and Exceptions
^
Front-end - 1257
SyntaxError: invalid syntax
Android - 1140
C++ - 1108
MySQL - 1045
The parser indicates the error line and displays ^ before the location where the error was detected.
Programming - 1042
abnormal network - 904
Even if a statement or expression is syntactically correct, it can cause errors when executed. Errors detected during data structure - 866
runtime are called exceptions Attribute - 865
C - 742
What I don't know in the learning process can add to me
xml - 735
python Learning buckle qun,784758214
//There are good practical courses, development tools and e-books in the group
less - 697
//Share with you the current talent needs of python enterprises and how to learn python from scra github - 694
>>> 10 * (1/0)
>>> 4 + spam*3
>>> '2' + 2
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.
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.
... try:
... break
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:
... 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
try:
raise cls()
except D:
print("D")
except C:
print("C")
except B:
print("B")
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 ValueError:
except:
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:
try:
f = open(arg, 'r')
except OSError:
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.
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
>>> try:
...
<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:
...
<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:
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:
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
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):
pass
class InputError(Error):
Attributes:
"""
self.expression = expression
self.message = message
class TransitionError(Error):
allowed.
Attributes:
p g g
next -- attempted new state
"""
self.previous = previous
self.next = next
self.message = message
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.
>>> try:
... finally:
...
Goodbye, world!
KeyboardInterrupt
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.
... try:
... result = x / y
... else:
... finally:
...
>>> divide(2, 1)
result is 2.0
>>> divide(2, 0)
division by zero!
finally clauses are often used to release external resources (such as files or network connections).
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
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.