A brief discussion on exception handling in Python
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)
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("别的错误")

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

This tutorial demonstrates how to use Python to process the statistical concept of Zipf's law and demonstrates the efficiency of Python's reading and sorting large text files when processing the law. You may be wondering what the term Zipf distribution means. To understand this term, we first need to define Zipf's law. Don't worry, I'll try to simplify the instructions. Zipf's Law Zipf's law simply means: in a large natural language corpus, the most frequently occurring words appear about twice as frequently as the second frequent words, three times as the third frequent words, four times as the fourth frequent words, and so on. Let's look at an example. If you look at the Brown corpus in American English, you will notice that the most frequent word is "th

This article explains how to use Beautiful Soup, a Python library, to parse HTML. It details common methods like find(), find_all(), select(), and get_text() for data extraction, handling of diverse HTML structures and errors, and alternatives (Sel

Dealing with noisy images is a common problem, especially with mobile phone or low-resolution camera photos. This tutorial explores image filtering techniques in Python using OpenCV to tackle this issue. Image Filtering: A Powerful Tool Image filter

Python provides a variety of ways to download files from the Internet, which can be downloaded over HTTP using the urllib package or the requests library. This tutorial will explain how to use these libraries to download files from URLs from Python. requests library requests is one of the most popular libraries in Python. It allows sending HTTP/1.1 requests without manually adding query strings to URLs or form encoding of POST data. The requests library can perform many functions, including: Add form data Add multi-part file Access Python response data Make a request head

PDF files are popular for their cross-platform compatibility, with content and layout consistent across operating systems, reading devices and software. However, unlike Python processing plain text files, PDF files are binary files with more complex structures and contain elements such as fonts, colors, and images. Fortunately, it is not difficult to process PDF files with Python's external modules. This article will use the PyPDF2 module to demonstrate how to open a PDF file, print a page, and extract text. For the creation and editing of PDF files, please refer to another tutorial from me. Preparation The core lies in using external module PyPDF2. First, install it using pip: pip is P

This tutorial demonstrates how to leverage Redis caching to boost the performance of Python applications, specifically within a Django framework. We'll cover Redis installation, Django configuration, and performance comparisons to highlight the bene

Natural language processing (NLP) is the automatic or semi-automatic processing of human language. NLP is closely related to linguistics and has links to research in cognitive science, psychology, physiology, and mathematics. In the computer science

This article compares TensorFlow and PyTorch for deep learning. It details the steps involved: data preparation, model building, training, evaluation, and deployment. Key differences between the frameworks, particularly regarding computational grap
