search
HomeBackend DevelopmentPython TutorialDetailed graphic explanation of Python exception handling methods

Python provides two very important functions to handle exceptions and errors that occur when python programs are running. You can use this feature to debug python programs.

We can open idle-->F1 to view the document. There are many exception types in it, as shown in the figure:

Detailed graphic explanation of Python exception handling methods

What is an exception?

An exception is an event that occurs during program execution and affects the normal execution of the program.

Generally, an exception occurs when Python cannot handle the program normally.

Exception is a Python object that represents an error.

When an exception occurs in a Python script, we need to catch and handle it, otherwise the program will terminate execution.

Exception handling

To catch exceptions, try/except statements can be used.

The try/except statement is used to detect errors in the try statement block, so that the except statement can capture the exception information and handle it.

If you don't want to end your program when an exception occurs, just catch it in try.

Grammar:

The following is the syntax of a simple try....except...else:

try :

##        #Run other code

except

# ##If a 'name' exception is raised in the try part##except

, :

##<statement> ​ ​ </statement>#If a 'name' exception is raised, get additional data

else:

# ​ ​ #If not Exception occurs

The working principle of try is that when a try statement is started, python marks it in the context of the current program, so that when an exception occurs, it can return here, try The clause is executed first, and what happens next depends on whether an exception occurs during execution. 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 it is in A new exception is thrown when handling the exception). #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 error Provincial error message).

#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.

Example

The following is a simple example, it opens a file, writes the content in the file, and no exception occurs:

#!/usr/bin/python

try:

fh

=

open("testfile", "w") fh.write(

"This is my test file for exception handling!!"

)##except IOError:

print "Error: can\'t find file or read data"

else:

print "Written content in the file successfully"

fh.close()

Output result of the above program:

Written content in the file successfully

Example

The following is a simple example, it opens a file and writes the content in the file, but the file does not have write permission, and an exception occurred. :

#!/usr/bin/python

##try:

fh = open(" testfile", "r")

fh .write("This is my test file for exception handling!!")

except IOError:

##print "Error: can\'t find file or read data"

else:

##​

print "Written content in the file successfully"##The above program output result:

Error : can't find

file or read dataUse except without any exception type You can use except without any exception type, as shown in the following example:

try

:

You do your operations here;

.......... ............except

:

If there is any exception, then execute this block.

........................else

:

If there is no exception then execute this block.The try-except statement in the above way captures all exceptions that occur. But this is not a good way, we cannot identify specific abnormal information through this program. Because it catches all exceptions. Use except with multiple exception types

You can also use the same except statement to handle multiple exception messages, as shown below:

try

:

##You do your operations here;

........................

<p style="text-align: left;"><span style="color: #ff0000"><code>except(Exception1[, Exception2[,...ExceptionN]]]):

If there is any exception from the given exception list,

##then execute this block.

##........................

else:

##If there is no exception then execute this block.try-finally statement

try-finally statement will execute the last code regardless of whether an exception occurs.

try

:#

finally

:

#Exit

raise

##Note: You can use the except statement or finally statement, but both cannot be used at the same time. The else statement cannot be used together with the finally statement

#!/usr/bin/python

try:

fh

= open ("testfile", "w") fh.write(

"This is my test file for exception handling!!")##finally:

print

"Error: can\'t find file or read data"

If the opened file does not have writable permissions, the output will be as follows: Error: can't find

file

or

read dataThe same example can also be written as follows: #!/usr/bin/python

try:

fh

=

open("testfile" , "w")##  try:

       fh.write("This is my test file for exception handling!!"

)##finally:

      print "Going to close the file"

#          fh.close( )

except IOError:

print "Error: can\'t find file or read data"

When in try An exception is thrown in the block and the finally block code is executed immediately.

After all statements in the finally block are executed, the exception is raised again and the except block code is executed.

The content of the parameter is different from the exception.

Exception parameters

An exception can take parameters, which can be used as output exception information parameters.

You can capture exception parameters through the except statement, as follows:

try:

You do your operations here;

..... ............

<p style="text-align: left;"><span style="color: #ff0000"><code>except ExceptionType, Argument:

You can print value of Argument here...

Exception values ​​received by variables are usually included in the exception statement. Variables in the form of tuples can receive one or more values.

Tuples usually contain error strings, error numbers, and error locations.

Example

The following is an example of a single exception:

#!/usr/bin/python

# Define a function here.

##def temp_convert(var):

try:

return int(var)

##except ValueError, Argument:

##         

print "The argument does not contain numbers\n", Argument

Call above function here.

##temp_convert(

"xyz "

);The execution result of the above program is as follows:

The argument does

not contain numbers##invalid literal

for

int() with base 10: 'xyz'Trigger exceptionWe can use the raise statement to trigger the exception ourselves

raise syntax format is as follows:

##raise

[Exception [, args [, traceback]]]

Exception in the statement is the type of exception (for example, NameError) parameter is an exception parameter value. This parameter is optional, if not provided, the exception parameter is "None". The last parameter is optional (rarely used in practice) and, if present, is the trace exception object. Example

An exception can be a string, class or object. Most of the exceptions provided by the Python kernel are instantiated classes, which are parameters of an instance of a class.

Defining an exception is very simple, as follows:

def

functionName(level):

if

level 1:

      raise "Invalid level!", level

      # The code below to this would not be executed

#       # if we raise the exception

Note: In order to catch exceptions, the "except" statement must use the same exception to throw the class object or string.

For example, if we catch the above exception, the "except" statement is as follows:

try:

Business Logic here...

except "Invalid level!" :

##Exception handling here...

else:

Rest of the code here...User-Defined Exceptions

Programs can name their own exceptions by creating a new exception class. Exceptions should typically inherit from the Exception class, either directly or indirectly.

The following are examples related to RuntimeError. A class is created in the example. The base class is RuntimeError, which is used to output more information when an exception is triggered.

In the try statement block, the except block statement is executed after the user-defined exception. The variable e is used to create an instance of the Networkerror class.

class Networkerror(RuntimeError):

def __init__(self, arg):

##                            

.args = argAfter you define the above class, you can trigger the exception as follows:

try

:

##raise Networkerror("Bad hostname")##except

Networkerror,e:

print

e.args

The above is the detailed content of Detailed graphic explanation of Python exception handling methods. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
How to Use Python to Find the Zipf Distribution of a Text FileHow to Use Python to Find the Zipf Distribution of a Text FileMar 05, 2025 am 09:58 AM

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

How Do I Use Beautiful Soup to Parse HTML?How Do I Use Beautiful Soup to Parse HTML?Mar 10, 2025 pm 06:54 PM

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

Image Filtering in PythonImage Filtering in PythonMar 03, 2025 am 09:44 AM

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

How to Work With PDF Documents Using PythonHow to Work With PDF Documents Using PythonMar 02, 2025 am 09:54 AM

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

How to Cache Using Redis in Django ApplicationsHow to Cache Using Redis in Django ApplicationsMar 02, 2025 am 10:10 AM

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

How to Perform Deep Learning with TensorFlow or PyTorch?How to Perform Deep Learning with TensorFlow or PyTorch?Mar 10, 2025 pm 06:52 PM

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

Introduction to Parallel and Concurrent Programming in PythonIntroduction to Parallel and Concurrent Programming in PythonMar 03, 2025 am 10:32 AM

Python, a favorite for data science and processing, offers a rich ecosystem for high-performance computing. However, parallel programming in Python presents unique challenges. This tutorial explores these challenges, focusing on the Global Interprete

How to Implement Your Own Data Structure in PythonHow to Implement Your Own Data Structure in PythonMar 03, 2025 am 09:28 AM

This tutorial demonstrates creating a custom pipeline data structure in Python 3, leveraging classes and operator overloading for enhanced functionality. The pipeline's flexibility lies in its ability to apply a series of functions to a data set, ge

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)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools