Ten common exception types in Python (with capture and exception handling methods)


insert image description here

foreword

Hello everyone, I am Brother Latiao! Today, I will tell you about the problems that will arise when we first start writing code-the common exceptions and how to deal with them at the beginning!

An exception refers to an error or abnormal situation that occurs during the running of the program, such as dividing by 0, accessing a variable that does not exist, and so on. Python provides some built-in exception types and also supports custom exception types.

If you want to find Brother Latiao, just click here, and you can take away some Python related information before Latiao:insert image description here

Ten types of abnormalities

1.TypeError

Raised when an operation or function is applied to an object of an inappropriate type.
For example:

a = 5 + '10'

In this example, we are trying to add the integer 5 and the string '10', which is not allowed because they are different types.

2.ValueError

Raised when an argument to a function or operation has the correct type but is not legal.
For example:

int('abc')

In this example, we are trying to convert the string 'abc' to an integer, but 'abc' is not a valid integer, so a ValueError is raised.

3.NameError

A NameError is thrown when trying to access an undefined variable.
For example:

print(x)

In this example, we try to print the value of the variable x, but x is not defined, so a NameError exception is raised.

4.IndexError

Raised when an attempt is made to access an index that does not exist in a list, tuple, or string.
For example:

a = [1, 2, 3]
print(a[3])

In this example, we are trying to access the fourth element of list a, but a has only three elements, so an IndexError exception is raised.

5.KeyError

Raised when an attempt is made to access a key that does not exist in the dictionary.
For example:

d = {
    
    'a': 1, 'b': 2}
print(d['c'])

In this example, we are trying to access the key 'c' which does not exist in the dictionary d, so a KeyError exception is raised.

6.ZeroDivisionError

Raised when an attempt is made to divide by zero.
For example:

a = 5 / 0

In this example, we are trying to divide 5 by 0, which is not allowed because the divisor cannot be zero, so a ZeroDivisionError exception is raised.

7.IOError

Raised when an attempt is made to read a file that does not exist or cannot be accessed.
For example:

f = open('nonexistent_file.txt', 'r')

In this example, we are trying to open a non-existent file nonexistent_file.txt, so an IOError will be raised.

8.ImportError

Raised when trying to import a module or package that doesn't exist.
For example:

import nonexistent_module

In this example, we try to import a non-existent module nonexistent_module, so an ImportError exception is raised.

9.AttributeError

Raised when an attempt is made to access a property of an object that does not exist.
For example:

s = 'hello'
print(s.uppercase())

In this example, we are trying to call the non-existent method uppercase() of the string s, thus raising an AttributeError exception.

10.KeyboardInterrupt

Raised when the user interrupts program execution.
For example:

while True:
    try:
        x = input('Enter a number: ')
        break
    except KeyboardInterrupt:
        print('You pressed Ctrl+C!')

In this example, we wait in an infinite loop for the user to enter a number, but if the user presses Ctrl+C, the program raises a KeyboardInterrupt exception, which we can catch and print a message.

Exception capture and handling

In Python, you can use the try-except statement to catch exceptions and handle them. The try statement block contains code that may cause exceptions. If an exception occurs, it will jump to the except statement block for processing. You can use multiple except statement blocks to handle different types of exceptions, or you can use one except statement block to handle all types of exceptions.

For example:

try:
    x = 1 / 0
except ZeroDivisionError:
    print("除以0错误")

In addition to using the built-in exception types, you can also customize exception types. Custom exception types are usually inherited from the Exception class or its subclasses. For example:

class MyException(Exception):
    pass

try:
    raise MyException("自定义异常")
except MyException as e:
    print(e)

In Python, you can also use a finally block to define code that needs to be executed regardless of whether an exception occurs. For example:

try:
    x = 1 / 0
except ZeroDivisionError:
    print("除以0错误")
finally:
    print("finally语句块")

Summarize

The above are common exception types and exception handling methods in Python. When writing a program, exceptions should be avoided as much as possible, and possible exceptions should be handled reasonably.

↓ ↓ ↓ Latiao business card below, various source codes + cases ↓ ↓ ↓

insert image description here

Guess you like

Origin blog.csdn.net/AI19970205/article/details/130957018