search
HomeBackend DevelopmentPython TutorialException handling in python (code example)

The content this article brings to you is about exception handling (code examples) in python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

When we think that some code may go wrong, we can use try to run this code. If an error occurs, the subsequent code will not continue to execute, but will jump directly to the error handling code, that is except statement block, after executing except, if there is a finally statement block, the finally statement block will be executed. At this point, the execution is completed.

Python’s try statement has two styles

  1. Handling exceptions (try/except/else)

  2. The first is that the last code (try/finally) will be executed regardless of whether an exception occurs.

try/except/else style

try:
    <语句> #运行别的代码
except <名字>: 
    <语句> #如果在try部份引发了&#39;name&#39;异常
except <名字>,<数据>:
    <语句> #如果引发了&#39;name&#39;异常,获得附加的数据
else:
    <语句> #如果没有异常发生

try The working principle is that when a try statement is started, python marks it in the context of the current program, so that when an exception occurs, you can return here. The try clause is executed first, and what happens next depends on whether it occurs during execution. abnormal.
1. If an exception occurs when the statement after try is executed, python will jump back to try and execute the first except clause matching the exception. After the exception is handled, the control flow will pass through the entire try statement (unless processing A new exception is thrown when an exception occurs).
2. If an exception occurs in the statement after try, but there is no matching except clause, the exception will be submitted to the upper try, or to the top level of the program (this will end the program and print the default error message).
3. If no exception occurs when the try clause is executed, python will execute the statement after the else statement (if there is an else), and then the control flow passes through the entire try statement.

try/finally style

try:
    <语句>
finally:
    <语句> #退出try时总会执行finally语句

Python will always execute the finally clause, regardless of whether an exception is thrown when the try clause is executed.
1. If no exception occurs, python runs the try clause, then the finally clause, and then continues.
2. If an exception occurs in the try clause, python will come back to execute the finally clause, and then submit the exception to the upper try. The control flow will not pass through the entire try statement.

try/finally is useful when you want to ensure that certain code is executed regardless of whether an exception occurs.

This is useful when opening a file, finally always close() the file at the end

try statement clause form table
except: catch all exceptions
except name: catch only Specific exceptions
except name,value: Catch the exception and its additional data (save the exception information to value,)
except (name1,name2): Catch any listed exceptions
else: if No exception
finally: always executed

try:
   f = open(&#39;file.txt&#39;)
except IOError as e:
   print e
else:
   print &#39;wrong&#39;
[Errno 2] No such file or directory: &#39;file.txt&#39;

try/except/finally:

#1:如果x没有异常,执行z,i
#2:如果x有异常, 
#一:如果except捕捉到异常则执行y,i
#二:没捕捉到,执行i,然后返回内置异常处理 

try: 
    x 
except(name): 
    y
else:
    z
finally:
    i

The above is the detailed content of Exception handling in python (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?Apr 02, 2025 am 07:12 AM

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),