search
HomeBackend DevelopmentPython TutorialPython error and exception concepts
Python error and exception conceptsFeb 28, 2017 am 10:32 AM
python

Python Error and Exception Concepts (General)

1. How to handle errors and exceptions

  1. Common Errors

  2. a: NameError

  3. if True: SyntaxError

  4. f = oepn('1.txt'): IOError

  5. 10/0: ZeropisionError

  6. a = int('d'): ValueError

  7. Program Running interruption: KeyboardInterrupt

2.Python-use try_except to handle exceptions (1)

try:
    try_suite
except Exception [e]:
    exception_block
  1. try is used to capture errors in try_suite, and Handle the error to except

  2. except is used to handle exceptions. If handling exceptions is consistent with setting captured exceptions, use exception_block to handle exceptions

# case 1
try:
    undef
except:
    print 'catch an except'
# case 2
try:
    if undef
except:
    print 'catch an except'
  • case1: The exception can be caught because it is a runtime error

  • case2: The exception cannot be caught because it is a syntax error and a pre-run error

--

# case 3
try:
    undef
except NameError,e:
    print 'catch an except',e
# case 4
try:
    undef
except IOError,e:
    print 'catch an except',e
  • case3: The exception can be caught because the catch NameError exception is set

  • case4: The exception cannot be caught because Setting IOError will not handle NameError

Example
import random

num = random.randint(0, 100)

while True:
    try:
        guess = int(raw_input("Enter 1~100"))
    except ValueError, e:
        print "Enter 1~100"
        continue
    if guess > num:
        print "guess Bigger:", guess
    elif guess < num:
        print "guess Smaller:", guess
    elif guess == num:
        print "Guess OK,Game Over"
        break
    print &#39;\n&#39;

3. Python uses try_except to handle exceptions (2)

  • try -except: handle multiple exceptions

try:
    try_suite
except Exception1[e]:
    exception_block1
except Exception2[e]:
    exception_block2
except ExceptionN[e]:
    exception_blockN

4. Python-try_finally uses

try:
    try_suite
finally:
    do_finally
  • If the try statement does not catch the error, the code executes the do_finally statement

  • If the try statement catches an error, the program first executes the do_finally statement, and then hands the captured error to the python interpreter for processing

5. Python -try-except-else-finally

 try:
    try_suite
 except:
    do_except
 finally:
    do_finally
  • If the try statement does not catch the exception, after executing the try code segment, execute finally

  • If try catches the exception, first executes except to handle the error, and then executes finally

6. Python-with_as statement

with context [as var]:
    with_suite
  • with statement is used to replace try_except_finall statement to make the code more concise

  • The context expression returns an object

  • var is used to save the context return object, a single return value or a tuple

  • with_suite uses var variables to operate on the context return object

The essence of the with statement is context management:

  1. Context management protocol: Contains methods __enter__() and __exit()__. Objects that support this protocol must implement these two methods

  2. Context manager: defines the runtime context to be established when executing the with statement, and is responsible for executing the entry and exit operations in the context of the with statement block

  3. Enter the context manager: call Manager __enter__ method, if the as var statement is set, the var variable accepts __enter__() method return value

  4. Exit the context manager: call Manager__exit__Method

class Mycontex(object):
    def __init__(self, name):
        self.name = name

    def __enter__(self):
        print "__enter__"
        return self

    def do_self(self):
        print "do_self"

    def __exit__(self, exc_type, exc_val, exc_tb):
        print "__exit__"
        print "Error:", exc_type, " info:", exc_val


if __name__ == "__main__":
    with Mycontex(&#39;test context&#39;) as f:
        print f.name
        f.do_self()

whith statement application scenario:

  1. File operation

  2. Mutual exclusion objects between process threads, such as mutex locks

  3. Other objects that support context

2. Standard exceptions and Automatically with exception

1. Python-assert and raise statements

  • rais statement

    • reise statement is used Actively throw exceptions

    • Syntax format: raise[exception[,args]]

    • exception: exception class

    • args: Tuple describing exception information

raise TypeError, &#39;Test Error&#39;
raise IOError, &#39;File Not Exit&#39;
  • assert statement

    • Assertion statement: The assert statement is used to check whether the expression is true. If it is false, an AssertionError is raised.

    • Syntax format: assert expression[,args]

    • experession: expression

    • args: description information of the judgment condition

assert 0, &#39;test assert&#39;
assert 4==5, &#39;test assert&#39;

2. Python-Standard Exceptions and custom exceptions

  • Standard exceptions

    • Python built-in exceptions already exist before the program is executed

    • Python error and exception concepts

  • Custom exceptions:

    • Python allows custom exceptions, Used to describe exceptions not involved in python

    • Custom exceptions must inherit the Exception class

    • Custom exceptions can only be actively triggered

class CustomError(Exception):
    def __init__(self, info):
        Exception.__init__(self)
        self.message = info
        print id(self)

    def __str__(self):
        return &#39;CustionError:%s&#39; % self.message


try:
    raise CustomError(&#39;test CustomError&#39;)
except CustomError, e:
    print &#39;ErrorInfo:%d,%s&#39; % (id(e), e)


For more articles related to Python errors and exception concepts, please pay attention to the PHP Chinese website!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
详细讲解Python之Seaborn(数据可视化)详细讲解Python之Seaborn(数据可视化)Apr 21, 2022 pm 06:08 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

详细了解Python进程池与进程锁详细了解Python进程池与进程锁May 10, 2022 pm 06:11 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

Python自动化实践之筛选简历Python自动化实践之筛选简历Jun 07, 2022 pm 06:59 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

归纳总结Python标准库归纳总结Python标准库May 03, 2022 am 09:00 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于标准库总结的相关问题,下面一起来看一下,希望对大家有帮助。

Python数据类型详解之字符串、数字Python数据类型详解之字符串、数字Apr 27, 2022 pm 07:27 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

分享10款高效的VSCode插件,总有一款能够惊艳到你!!分享10款高效的VSCode插件,总有一款能够惊艳到你!!Mar 09, 2021 am 10:15 AM

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

详细介绍python的numpy模块详细介绍python的numpy模块May 19, 2022 am 11:43 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。

python中文是什么意思python中文是什么意思Jun 24, 2019 pm 02:22 PM

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools