Table of Contents
Common Errors
2.Python-use try_except to handle exceptions (1)
Example
3. Python uses try_except to handle exceptions (2)
4. Python-try_finally uses
5. Python -try-except-else-finally
6. Python-with_as statement
The essence of the with statement is context management:
whith statement application scenario:
2. Standard exceptions and Automatically with exception
1. Python-assert and raise statements
2. Python-Standard Exceptions and custom exceptions
Home Backend Development Python Tutorial Python error and exception concepts

Python error and exception concepts

Feb 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
Copy after login
  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'
Copy after login
# case 2
try:
    if undef
except:
    print 'catch an except'
Copy after login
  • 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
Copy after login
# case 4
try:
    undef
except IOError,e:
    print 'catch an except',e
Copy after login
  • 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;
Copy after login

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
Copy after login

4. Python-try_finally uses

try:
    try_suite
finally:
    do_finally
Copy after login
  • 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
Copy after login
  • 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
Copy after login
  • 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()
Copy after login

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;
Copy after login
raise IOError, &#39;File Not Exit&#39;
Copy after login
  • 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;
Copy after login
assert 4==5, &#39;test assert&#39;
Copy after login

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)
Copy after login


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


Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Can vscode be used for mac Can vscode be used for mac Apr 15, 2025 pm 07:36 PM

VS Code is available on Mac. It has powerful extensions, Git integration, terminal and debugger, and also offers a wealth of setup options. However, for particularly large projects or highly professional development, VS Code may have performance or functional limitations.

Golang vs. Python: Concurrency and Multithreading Golang vs. Python: Concurrency and Multithreading Apr 17, 2025 am 12:20 AM

Golang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles