Python 8_warning and exception

Source: Internet
Author: User

The mood is a bit tangled. What should I do? It's not because of other learning things, but because the story of dog blood in life forces people to deviate and get farther away. It is also normal for people to misunderstand people, it may be because the communication is not enough and they do not know each other well. I hope that I can spend this tangled day, simple life, taste, and think carefully as soon as possible.

Recently, I borrowed a Python Cookbook as needed, and found that this book has a good introduction in many aspects, such as system management, web, and distributed programming, data Persistence and so on. However, I have not found any detailed introductions about errors and exceptions. I plan to study the errors and exceptions with a dead attitude.

First, let's take a look at the example program:


First of all, what we see here is not an exception, but another non-fatal warning that we often encounter, mainly to provide users with non-fatal warnings, pointing out the problems encountered when running a program. Generally, we 'd better avoid such things in the program, otherwise we will need to review our code. <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD48aDE + release/y + r7jmPC9oMT48cD6 + release/release + a1xM/release + lNb2R1bGWw/release + vJ + rPJvq + 45 rXExKO/release + r7jms/release/tbHJ + release /examples/cLLxve9q7/Y1sbV4rj2vq + 45rLJyKG1xLav1/examples/X96OsxuTKtbG + 1srb97ppc3 + samples + examples/ejuw.vcd48dgfibgu + outputs = "top">

Action

Description

Error

Raise the warning to an exception

Ignore

Ignore warning

Always

Always throw a warning

Default

Generates a warning for the first time from each location

Module

Generates a warning when each module generates a warning for the first time.

Once

Output warning when warning is generated for the first time

1. Pattern Filtering

Simple filtering, for example, show_warning_by_filtering () in the example, uses filterwarning () to filter messages based on more complex rules by programming. For example, you need to filter messages based on text content, A regular expression can be provided as an event. For example, show_pattern_filter () in the example. The mode contains 'do not '. The specific message uses 'do not'. The regular expression is compiled into a case-insensitive match, therefore, this mode will match. Of course, the same match applies to the source module name. You can pass the module name as the mode to the module parameter to suppress all messages from the copy module, as shown below:


Of course, we can also restrict only warnings on a row, as shown below:


2. Repeated warnings

By default, most warnings are output only when a given position appears for the first time. However, if a warning appears in our program, we find that there is a same warning after the change, at this time, there will be an illusion that we don't know when it is a head. The most direct way is to give him a warning in every warning place. At least we can be aware of it, as follows:


3. Warning targeted output

Generally, warnings are output to sys. stderr. We can change this behavior by replacing the showwarning () function in the warning module, as shown below:


Note: Here, UserWarning is a warning type, which is the base class of the warning from the user code. There are some other types, such:

Warning ----- base classes of all warnings

DeprecationWarning ---- a feature that is no longer maintained

PendingDeprecationWarning ---- used for features that will soon be discarded

SyntaxWarning --- used for problematic syntax

RuntimeWarning-used for running events that may cause problems

FutureWarning-warnings about possible changes to future languages or libraries

ImportWarning warning about problems in the import module

UnicodeWarning --- warning about Unicode text Problems

Ii. Exception ---- built-in Exception class 1. Exception base class

BaseException:

All the base classes with exceptions implement the logic of the base class. You can use str () to create an exception string representation by the parameters passed in the constructor.

Exception:

Some exceptions do not cause exiting running applications. Exception is the base class of all these exceptions. All user-defined exceptions should be treated as the base class.

StandardError:

Base classes with built-in exceptions used in the standard library

ArithmeticError:

Math-related error base class

LookupError:

The base class of the error generated when an object cannot be found

EnvironmentError:

Base classes with errors from Python external (operating system, file system, etc.)

2. Common exceptions

Here, we only use AssertionError as an example. AssertionError is generated by a failed assert statement. AssertionError is common in the database and is usually used to restrict input parameters. It is similar to failif () assertionError can also be used in the Automatic Test created by the unittest module. The program running the automatic test suite monitors AssertionError exceptions as a special prompt for test failure, as shown below:

OSError is generated when system-level functions return errors.

OverflowError: When an arithmetic operation exceeds the limitation of the variable type

RefernceError:

When a weakref proxy is used to access a garbage collection object

RuntimeError: If no other more specific exception is available, use the RuntimeError exception.

SyntaxError: When the interpreter cannot interpret the program

SystemError: if an error occurs in the explanation

SystemExit: When sys. exit () is called

TypeError: if the object type is incorrect when a function is called based on an object or an object

UnboundLocalError: A NameError, especially for local variable names.

UnicodeError: a subclass of ValueError, which is generated when a Unicode problem occurs.

ValueError: If a function receives a correct value type, but the value is invalid

ZeroDivisionError: 0 is thrown when the denominator is set.

Note: We may often encounter exceptions in the program first, but the most important thing is that it will be helpful for programming and debugging programs in the future, for the error information, you can immediately determine where the problem has occurred. This is the most important part.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.