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 do you append elements to a Python array?How do you append elements to a Python array?Apr 30, 2025 am 12:19 AM

InPython,youappendelementstoalistusingtheappend()method.1)Useappend()forsingleelements:my_list.append(4).2)Useextend()or =formultipleelements:my_list.extend(another_list)ormy_list =[4,5,6].3)Useinsert()forspecificpositions:my_list.insert(1,5).Beaware

How do you debug shebang-related issues?How do you debug shebang-related issues?Apr 30, 2025 am 12:17 AM

The methods to debug the shebang problem include: 1. Check the shebang line to make sure it is the first line of the script and there are no prefixed spaces; 2. Verify whether the interpreter path is correct; 3. Call the interpreter directly to run the script to isolate the shebang problem; 4. Use strace or trusts to track the system calls; 5. Check the impact of environment variables on shebang.

How do you remove elements from a Python array?How do you remove elements from a Python array?Apr 30, 2025 am 12:16 AM

Pythonlistscanbemanipulatedusingseveralmethodstoremoveelements:1)Theremove()methodremovesthefirstoccurrenceofaspecifiedvalue.2)Thepop()methodremovesandreturnsanelementatagivenindex.3)Thedelstatementcanremoveanitemorslicebyindex.4)Listcomprehensionscr

What data types can be stored in a Python list?What data types can be stored in a Python list?Apr 30, 2025 am 12:07 AM

Pythonlistscanstoreanydatatype,includingintegers,strings,floats,booleans,otherlists,anddictionaries.Thisversatilityallowsformixed-typelists,whichcanbemanagedeffectivelyusingtypechecks,typehints,andspecializedlibrarieslikenumpyforperformance.Documenti

What are some common operations that can be performed on Python lists?What are some common operations that can be performed on Python lists?Apr 30, 2025 am 12:01 AM

Pythonlistssupportnumerousoperations:1)Addingelementswithappend(),extend(),andinsert().2)Removingitemsusingremove(),pop(),andclear().3)Accessingandmodifyingwithindexingandslicing.4)Searchingandsortingwithindex(),sort(),andreverse().5)Advancedoperatio

How do you create multi-dimensional arrays using NumPy?How do you create multi-dimensional arrays using NumPy?Apr 29, 2025 am 12:27 AM

Create multi-dimensional arrays with NumPy can be achieved through the following steps: 1) Use the numpy.array() function to create an array, such as np.array([[1,2,3],[4,5,6]]) to create a 2D array; 2) Use np.zeros(), np.ones(), np.random.random() and other functions to create an array filled with specific values; 3) Understand the shape and size properties of the array to ensure that the length of the sub-array is consistent and avoid errors; 4) Use the np.reshape() function to change the shape of the array; 5) Pay attention to memory usage to ensure that the code is clear and efficient.

Explain the concept of 'broadcasting' in NumPy arrays.Explain the concept of 'broadcasting' in NumPy arrays.Apr 29, 2025 am 12:23 AM

BroadcastinginNumPyisamethodtoperformoperationsonarraysofdifferentshapesbyautomaticallyaligningthem.Itsimplifiescode,enhancesreadability,andboostsperformance.Here'showitworks:1)Smallerarraysarepaddedwithonestomatchdimensions.2)Compatibledimensionsare

Explain how to choose between lists, array.array, and NumPy arrays for data storage.Explain how to choose between lists, array.array, and NumPy arrays for data storage.Apr 29, 2025 am 12:20 AM

ForPythondatastorage,chooselistsforflexibilitywithmixeddatatypes,array.arrayformemory-efficienthomogeneousnumericaldata,andNumPyarraysforadvancednumericalcomputing.Listsareversatilebutlessefficientforlargenumericaldatasets;array.arrayoffersamiddlegro

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

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.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.