Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the basic knowledge of Python exception handling

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces the basic knowledge of Python exception handling, the article is very detailed, has a certain reference value, interested friends must read it!

1. Python exception handling: errors and exceptions 1. What is an error?

An error is an error in a program, such as a syntax error.

It happens at compile time. Let's look at an example.

If a > > 1 / 0Traceback (most recent call last): File ", line 301, in run code File", line 1, in ZeroDivisionError: division by zero II, how to use Try-Except to handle exceptions? 1. What is a Try-Except statement?

We use the try-except statement to enable exception handling in the Python program.

In the try block, you write code that throws an exception.

For code that handles or catches exceptions, we put them in the except clause.

2. Python exception handling syntax

The following is the syntax of the Python try-except-else block.

Try: you do your operation here;.. except ExceptionI: if there is ExceptionI, execute this block except ExceptionII: if there is ExceptionII, execute this block.. else: execute this block if there are no exceptions.

Take a look-30 Python tutorials and tips

This is a list of valid Python try statements.

Depending on your requirements, a single try statement can have multiple except statements. In this case, the try block contains statements that can throw different types of exceptions.

We can also add a generic except clause that handles all possible exception types.

We can even include an else clause after the except clause. If the code in the try block does not throw an exception, the instructions in the else block are executed.

3. Python exception handling example

Let's look at the use of Python try-except through a sample code.

Try: fob = open ("test", "w") fob.write ("this is my exception handling test file") except IOError: print "error: cannot find the file or read data" else: print "write to the file successfully" fob.close ()

The above code produces the following output.

The write operation to the file was successful

Let's give another example, in which we try to open a file in READ mode.

We will WRITE it. An exception is thrown during execution.

Try: fob = open ("test", "r") fob.write ("this is my test file to verify exception handling in Python") except IOError: print "error: unable to find file or read data" else: print "write to file successful"

The above code produces the following output.

> > error: cannot find file or read data

Use Except to handle all types of exceptions

If we use an empty "except" clause, it will catch all types of exceptions.

However, this is not a good programming habit, and no one recommends it.

This is because such Python try-except blocks can handle all types of exceptions. But it does not help programmers find the exception that is causing the problem.

You can see how to catch all exceptions from the following code.

1. Example try: you do your operation here;.. except: if there are any exceptions, execute this block. Else: execute this block if there are no exceptions. Fourth, use except to handle multiple exceptions.

We can use the same except clause to define multiple exceptions. This means that if the Python interpreter finds a matching exception, it will execute the code written under the except clause.

In short, when we define the except clause in this way, we expect the same piece of code to throw different exceptions. In addition, we hope to take the same action in each case.

Please refer to the following example.

1. Example try: you do your operation here (Exception1 [, Exception2 [,... ExceptionN]]): if there are any exceptions in the given exception list, then execute this block.. else: execute this block if there are no exceptions, how to use Try-Finally to handle exceptions? 1. What is a Try-Finally statement?

We can also enable Python exception handling with try-finally statements.

Using try blocks, we can also choose to define "finally" blocks. This clause allows you to define the statement we want to execute, whether or not the try block throws an exception.

This feature usually occurs when external resources are released.

This is a coding fragment of help.

Try: you do your operation here;. Due to any exception, this may be skipped finally: this will always be executed. 2. Example

One key point is that we can define a "except" or "finally" clause for each try block. You can't put these together. Also, you should not use the "else" clause with the "finally" clause.

Let's give an example to make it clearer.

Try: fob = open ('test', 'w') fob.write ("this is my test file for verifying try-finally in exception handling") print' try block executes' finally: fob.close () print 'finally block execution'

If no exception occurs, you will see the following output.

> > try block execution

> > finally block execution

Suppose we open the file in READ mode and then try to write to it. In this case, the following code will help handle the exception.

Try: fob = open ('test', 'r') try: fob.write ("this is the test file I validated try-finally during exception handling") print' try block executes' finally: fob.close () print 'finally block execution to close the file' except IOError: print "error: file not found or data read"

In this case, the interpreter throws an exception and displays the following output.

> > finally block execution to close the file

> > error: cannot find file or read data

When some code throws an exception in a try block, execution is immediately passed to the "finally" block. After all the statements in the "finally" block have been executed, the exception returns to the "except" block execution. But there must be the next higher level of the "try-except" statement.

6. Throw an exception with parameters. 1. What is ascension?

We can use the raise keyword to force an exception.

We can also choose to pass the value to the exception and specify the reason why it occurs.

2. Improve grammar

This is the syntax for calling the "raise" method.

Raise [Exception [, args [, traceback]

Where,

Under "Exception"-specify its name.

"args" is optional and represents the value of the exception parameter.

The last parameter, "traceback", is also optional and, if present, is the backtracking object for the exception.

Let's give an example to prove this.

3. Example > raise MemoryErrorTraceback (most recent call last):... MemoryError > raise MemoryError ("This is an argument") Traceback (most recent call last):... MemoryError: This is an argument > try: a = int ("Enter a positive integer value:") if a > > class UserDefinedError (Exception):. Pass > raise UserDefinedErrorTraceback (most recent call last):... _ main__.UserDefinedError > raise UserDefinedError ("An error occurred") Traceback (most recent call last):... _ main__.UserDefinedError: An error occurred

In the code snippet above, you can see that we have created a user-defined exception class, "UserDefinedError". It uses the base Exception class as the parent class. Therefore, the new user-defined exception class will throw an exception like any other exception class, that is, by calling a "raise" statement with an optional error message.

Let's give an example.

3. Examples

In this example, we will show how to throw a user-defined exception and catch an error in a program.

The program prompts the user to enter the alphabet again and again until he enters only the stored alphabet.

To ask for help, the program provides tips to the user so that he can find the correct alphabet. In addition, he can check whether his guess is higher or lower than the stored alphabet.

# define Python user-defined exception class Error (Exception): "Base class for other exceptions" pass class InputTooSmallError (Error): "Raised when the entered alpahbet is smaller than the actual one" pass class InputTooLargeError (Error): "Raised when the entered alpahbet is larger than the actual one" pass # our main program # user guesses a letter Until he / she guesses right # you need to guess the letter alphabet ='m 'while True: try: apb = input ("enter a letter:") if apb

< alphabet: raise InputTooSmallError elif apb >

Alphabet: raise InputTooLargeError break except InputTooSmallError: print ("the letter entered is too small, try again!") Print ('') except InputTooLargeError: print ("the letter entered is too big, try again!") Print ('') print ("Congratulations! you guessed right")

Let's test the program by providing different inputs.

Enter a letter: C the letter entered is too small, try again! Enter a letter: s the letter entered is too big, try again! Enter a letter: the letter entered by Q is too big, try again! Enter a letter: the letter k is too small, try again! Enter a letter: M Congratulations! You were right.

So you can see that we have defined a base class called Error in this program. It throws two exceptions ("InputTooSmallError" and "InputTooLargeError") derived from the base class. This is the standard way to define user-defined exceptions in Python programming.

4. Python built-in exception

These are all the contents of this article entitled "what are the basics of Python exception handling?" Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report