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("别的错误")

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

Python's statistics module provides powerful data statistical analysis capabilities to help us quickly understand the overall characteristics of data, such as biostatistics and business analysis. Instead of looking at data points one by one, just look at statistics such as mean or variance to discover trends and features in the original data that may be ignored, and compare large datasets more easily and effectively. This tutorial will explain how to calculate the mean and measure the degree of dispersion of the dataset. Unless otherwise stated, all functions in this module support the calculation of the mean() function instead of simply summing the average. Floating point numbers can also be used. import random import statistics from fracti

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

Serialization and deserialization of Python objects are key aspects of any non-trivial program. If you save something to a Python file, you do object serialization and deserialization if you read the configuration file, or if you respond to an HTTP request. In a sense, serialization and deserialization are the most boring things in the world. Who cares about all these formats and protocols? You want to persist or stream some Python objects and retrieve them in full at a later time. This is a great way to see the world on a conceptual level. However, on a practical level, the serialization scheme, format or protocol you choose may determine the speed, security, freedom of maintenance status, and other aspects of the program

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

This tutorial builds upon the previous introduction to Beautiful Soup, focusing on DOM manipulation beyond simple tree navigation. We'll explore efficient search methods and techniques for modifying HTML structure. One common DOM search method is ex

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

This article guides Python developers on building command-line interfaces (CLIs). It details using libraries like typer, click, and argparse, emphasizing input/output handling, and promoting user-friendly design patterns for improved CLI usability.


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

SublimeText3 English version
Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version
Useful JavaScript development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
