Home Backend Development Python Tutorial A brief discussion on exception handling in Python

A brief discussion on exception handling in Python

Jul 21, 2016 pm 02:53 PM

This article mainly introduces relevant information about Python's exception handling. Friends who need it can refer to it

Python's exception handling capability is very powerful and can accurately feedback error information to users. In Python, exceptions are also objects and can be manipulated. All exceptions are members of the base class Exception. All exceptions inherit from the base class Exception and are defined in the exceptions module. Python automatically places all exception names in the built-in namespace, so programs do not have to import the exceptions module to use exceptions. Python uses exception objects to represent abnormal situations. When an error is encountered, an exception will be thrown. If the exception object is not handled or caught, the program will terminate execution with a so-called traceback (an error message).

Note: Although most errors will result in an exception, an exception does not necessarily represent an error. Sometimes they are just a warning, and sometimes they may be a termination signal, such as exiting a loop, etc.

1. Keywords related to python exceptions

raise: manually throw/raise exceptions: raise [exception[,data]
try/except: Catch exceptions and handle
pass: ignore exceptions
as: define exception instance (except IOError as e)
finally: code that is executed regardless of whether an exception occurs]
else: if the statement in try If no exception is thrown, execute the statement in else
except Exception as error:

2. Exception types in python

1.StandardError class : If a logic error occurs in the program, this exception will be thrown. The StandardError class is the base class for all restrained exceptions and is placed in the default namespace. Therefore, there is no need to import the exception module when using IOEroor, EOFError, ImportError and other classes.

StopIteration class: Determine whether the loop is executed to the end. If the loop reaches the end, the exception is thrown.
GeneratorExit class: It is an exception raised by the Generator function. This exception is raised when close() is called.
Warning class: Represents warnings caused by code in the program.

3. Basic method:

1.try:

Statement 1

except [exception1(,exception2 ...),[data…]]:

Statement 2

else:

Statement 3

The rules of this exception handling syntax are:

· Execute the statement under try. If an exception is thrown, the execution process will jump to the first except statement.

· If the exception defined in the first except matches the exception raised, the statement in the except is executed.

· If the raised exception does not match the first except, the second except will be searched, and there is no limit to the number of excepts allowed to be written.

· If all excepts do not match, the exception will be passed to the next highest-level try code that calls this code.

· If no exception occurs, the else block code is executed.

import traceback
try:
  1/0
except Exception as err:
  print(err)
try:
  f = open("file.txt","r")
except IOError as e:
  print(e)
try:
  f = open("file.txt","r")
except Exception as e:
  print(e)
Copy after login

The output of the last two are exactly the same--------------------- -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- ----------------------------------------

2.try:

Statement 1

finally:

Statement 2

The execution rules of this statement are:

· Execute the code under try.

· If an exception occurs, when the exception is passed to the next level try, the code in finally is executed.

· If no exception occurs, the code in finally is executed.

The second try syntax is useful when code needs to be executed regardless of whether an exception occurs. For example, when we open a file in python for read and write operations, no matter whether there is an exception during the operation, I will eventually close the file. These two forms conflict with each other. If you use one, you are not allowed to use the other, and the functions are different

So, under normal circumstances, finally performs some cleaning work, such as: closing files Descriptors, release locks, etc.

Note that in finally, if an exception occurs, if there is no corresponding external capture mechanism, the exception will be thrown layer by layer until the top, and then the interpreter will stop. Generally, add a try except exception capture in the outer layer

3. Manually use raise to raise an exception

1.raise [exception[,data]]

2. In Python, to raise an exception, the simplest form is to enter the keyword raise, followed by the name of the exception to be raised. Exception names identify specific classes: Python exceptions are objects of those classes. When a raise statement is executed, Python creates an object of the specified exception class. The raise statement can also specify parameters for initializing the exception object. To do this, add a comma and the specified parameters (or a tuple of parameters) after the name of the exception class.

3. Example:

try:
  print("开始测试")
  raise IOError
except IOError:
  print("定义好的错误")
except:
  print("别的错误")
Copy after login


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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1247
24
Python vs. C  : Applications and Use Cases Compared Python vs. C : Applications and Use Cases Compared Apr 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.

Python: Games, GUIs, and More Python: Games, GUIs, and More Apr 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  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 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 and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 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.

Python vs. C  : Exploring Performance and Efficiency Python vs. C : Exploring Performance and Efficiency Apr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

See all articles