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

How to handle exceptions in Python

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

Share

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

The knowledge of this article "how to handle exceptions in Python" is not quite understood by most people, so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to deal with exceptions in Python" article.

Syntax for Python try and except blocks

Let's start by understanding the syntax of try and except statements in Python. The generic template is shown in the following figure:

Try: # There can be errors in this block except: # Do this to handle exception; # executed if the try block throws an error else: # Do this if try block executes successfully without errors finally: # This block is always executed

Let's look at the uses of different blocks:

The block of try code is the block of statements you want to try to execute. However, this block may not work as expected because the exception may have run-time errors.

The except code block is the statement that needs to be executed when the try block is triggered. It contains a set of statements that usually provide you with some handling of errors within the try block.

You should always mention the type of error you intend to catch as an exception within the code block, represented by the placeholders in the above code snippet. For example: except

You can also not specify it in except. However, this is not recommended because you do not consider the different types of errors that may occur.

Multiple errors can also occur when you try to execute code within a try block.

For example, you might be using an out-of-range index access list, using the wrong dictionary key, and trying to open a file that doesn't exist-all of which should be placed in a try block.

In this case, you may encounter IndexError,KeyError and FileNotFoundError. And you must add as many errors of each type as you expect from except.

The try block is triggered only if the else block is executed without errors. This can be useful when you want to perform subsequent actions after the try block is successful. For example, if you try to open a file successfully, you may need to read its contents.

The finally block is always executed, regardless of what happens in other blocks. This is useful when you want to release resources after a specific block of code is executed.

Note: else and finally blocks are optional. In most cases, you can just use the try block to try to do something and catch the error as an exception within the except block.

In the next few minutes, you will use what you have learned so far to handle exceptions in Python. Let's get started.

How to handle ZeroDivision (divide by Zero exception) errors in Python

Consider the function divide () shown below. It takes two parameters, num and div, and returns the quotient num/div of the division operation.

Def divide (num,div): return num/div

When ▶ calls the function with different parameters, the result is returned as expected:

Res = divide (100jing8) print (res) # Output12.5res = divide (568,564) print (res) # Output8.875

This code works fine until you try to divide it by zero:

Divide (27pr 0)

You will see the program crash and throw a ZeroDivisionError:

# Output----ZeroDivisionError Traceback (most recent call last) in ()-> 1 divide (27d0) in divide (num, div) 1 def divide (num Div):-> 2 return num/divZeroDivisionError: division by zero

You can divide this by zero as exception handling by doing the following:

In the try block, call the divide () function. In essence, you are trying to divide num by div.

When div is 0, it is handled as an exception within the except block.

In this example, you can exclude ZeroDivisionError exceptions by printing a message informing users that they are trying to divide by zero.

This is shown in the following code snippet:

Try: res = divide (num,div) print (res) except ZeroDivisionError: print ("You tried to divide by zero: (")

With valid input, the code still works.

Divide (10Pol 2) # Output5.0

When you try to remove 00:00, you will be notified that an exception has occurred and the program will end normally.

Divide (10memo) # OutputYou tried to divide by zero: (how to handle TypeError (type exception) in Python

In this section, you will see how to use try and except to process a TypeError in Python.

▶ considers the function add_10 (), which takes a number as a parameter, adds 10 to it, and returns the result of the addition.

Def add_10 (num): return num + 10

You can call the function with any numeric argument, and it will work as follows:

Result = add_10 (89) print (result) # Output99

Now try add_10 () to use "five" instead of calling 5.

Add_10 ("five")

You will notice that your program crashes and displays the following error message:

-TypeError Traceback (most recent call last) in ()-> 1 add_10 ("five") in add_10 (num) 1 def add_10 (num):-> 2 return num + 10TypeError: can only concatenate str (not "int") to str

The error message TypeError: can only concatenate str (not "int") to str states that you can only concatenate two strings and cannot add integers to the string.

Now, you have the following:

Given a numeric my_num, try calling the function add_10 () with my_num as an argument. If the parameter is a valid type, there is no exception

Otherwise, the except block corresponding to TypeError will be triggered, informing the user that the type of the parameter is invalid.

This is explained as follows:

My_num = "five" try: result = add_10 (my_num) print (result) except TypeError: print ("The argument `num` should be a number")

Because you have now handled TypeError as an exception, you will only be told that the type of the parameter is invalid.

How The argument `num` should be a number handles IndexError in Python (invalid index)

If you have used Python lists or any iterated Python data types before, you may encounter IndexError. Exe.

This is because it is often difficult to track all changes to iterable objects. And you may be trying to access an item at an invalid index.

▶ in this example, the list my_list has four items. If you use a negative index, the valid indexes are 0, 1, 2, and 3, and-1,-2,-3,-4.

Because 2 is a valid index, you can see that the items in index 2 are printed, that is, clocked indexes:

My_list = ["Python", "C", "C++", "JavaScript"] print (my_list [2]) # OutputC++

If you try to access an item at an index that is outside the range of a valid index, you will encounter IndexError:

Print (my_list [4])-IndexError Traceback (most recent call last) in () 1 my_list = ["Python", "C", "C++" "JavaScript"]-> 2 print (my_list [4]) IndexError: list index out of range

If you are familiar with this pattern, you will now use try and except to handle index errors.

▶ in the following code snippet, you try to access the project search_idx at the specified index.

Search_idx = 3try: print (my_ list [search _ idx]) except IndexError: print ("Sorry, the list index is out of range")

Here, search_idx (3) is a valid index and prints out the items at a specific index:

JavaScript

If the search_idx is out of the valid range of the index, the except block catches that the IndexError is an exception and there are no more error messages.

Search_idx = 4try: print (my_ list [search _ idx]) except IndexError: print ("Sorry, the list index is out of range")

Instead, it displays messages that search_idx is out of the range of a valid index:

Sorry, how does the list index is out of range handle KeyError in Python (key-value pair exception)

You may have encountered KeyError when using Python dictionaries.

▶ consider this example. You have a dictionary my_dict.

My_dict = {"key1": "value1", "key2": "value2", "key3": "value3"} search_key = "non-existent key" print (my_ operations [search _ key])

The dictionary my_dict has three key-value pairs, "key1:value1", "key2:value2", and "key3:value3"

Now you try to access the dictionary and access the value "non-existent key" corresponding to key.

As expected, you will get a KeyError:

-KeyError Traceback (most recent call last) in () 1 my_dict = {"key1": "value1", "key2": "value2" "key3": "value3"} 2 search_key = "non-existent key"-> 3 my_ key [search _ key] KeyError: 'non-existent key'

You can almost deal with KeyError as you would with IndexError.

You can try to access the value search_key corresponding to the specified key.

If search_key is indeed a valid key, the corresponding value is printed.

If you encounter an exception because the key does not exist, you can use the except block to let the user know.

This is explained in the following code fragment:

Try: print (my_ requests [search _ key]) except KeyError: print ("Sorry, that's not a valid key!") Sorry, that's not a valid key!

▶ if you want to provide other operations, such as the name of an invalid key, you can also do this: the key may be misspelled, making it invalid. In this case, letting the user know which key is used may help them fix spelling mistakes.

You can do this by capturing an invalid key and using it in messages printed when an exception occurs:

Try: print (my_ requests [search _ key]) except KeyError as error_msg: print (f "Sorry, {error_msg} is not a valid key!")

▶ notice how the key name is also printed:

Sorry,'non-existent key' is not a valid key! How to handle FileNotFoundError in Python (file cannot find exception)

Another common error that occurs when working with files in Python is FileNotFoundError.

▶ in the following example, you try to open the file my_file.txt by specifying the path to the open () function. And you want to read the file and print out its contents.

However, you have not created the file in the specified location.

If you try to run the following code snippet, you will get FileNotFoundError:

My_file = open ("/ content/sample_data/my_file.txt") contents = my_file.read () print (contents)-FileNotFoundError Traceback (most recent call last) in ()-> 1 my_file = open ("my_file.txt") FileNotFoundError: [Errno 2] No such file or directory: 'my_file.txt'

Using try and except, you can do the following:

Try to open the file in the try block.

Processing FileNotFoundError: let users know through except that they are trying to open a block of files that does not exist.

If the try block succeeds and the file does exist, the contents of the file are read and printed.

In the finally block, close the file to avoid wasting resources. Think about how the file will be closed, regardless of what happens in the file opening and reading steps.

Try: my_file = open ("/ content/sample_data/my_file.txt") except FileNotFoundError: print (f "Sorry, the file does not exist") else: contents = my_file.read () print (contents) finally: my_file.close ()

Notice how you treat the error as an exception, and the following message is gracefully displayed at the end of the program:

Sorry, the file does not exist

▶ asked us to consider the case of else trigger blocks. The file my_file.txt is now in the path mentioned earlier.

Now, rerun the previous code snippet and work as expected.

The above is about the content of this article on "how to handle exceptions in Python". I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please 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: 270

*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