Table of Contents
Exception
Errors and exceptions
Grammar Error
Exception handling
Throw independently Exception
Customized exceptions
finally子句
Home Backend Development Python Tutorial What is the method of exception handling in Python basic tutorial?

What is the method of exception handling in Python basic tutorial?

May 27, 2023 pm 09:24 PM
python

Exception

In Python, the exception object (exception object) is used to represent the abnormal situation that occurs during the execution of the code. When the executing program explodes In case of error, an exception will be thrown.

If the exception is not handled correctly, the operation will be terminated.

You can imagine that if you are developing a product and an exception occurs and you do not report the cause of the exception, it will be very uncomfortable and it will be difficult to solve the abnormal problem.

In order to improve the stability and flexibility of the product, Python runs developers to capture and handle various exceptions. General internal module errors such as KeyError exception class are more common , of course there are many others.

Errors and exceptions

For a brief understanding, Python divides code execution errors into two categories: syntax error(syntax error)and exception(exception).

Grammar Error

First of all, there is the problem of grammatical errors. It can be seen from the words that the code parsing error is wrong.

This kind of error usually occurs among beginners. The main reason is that the code being executed does not comply with the Python syntax specifications, so a syntax error will be reported and the code will stop.

An error example is given below:

>>> if for not in list(1,2,3,4)
  File "<stdin>", line 1
    if for not in list(1,2,3,4)
       ^
SyntaxError: invalid syntax
Copy after login

From the above error report, we can know that it is a syntax error and invalid syntax. And pointed out that the error is in the position of for. Obviously if and for cannot be used together.

Exception

Exception is an error found during the execution of the code. It is difficult to detect in advance. Even if the code is written in a very standard way, execution exceptions may occur. Condition.

An error example is given below. In mathematical operations, a frequently discussed problem is the case of dividing by zero. However, 0 is not allowed as a divisor because it would cause an exception.

>>> a = 5 / 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
Copy after login

Obviously the error message indicates that 0 is incorrect as the divisor.

Exception handling

After we understand errors and exceptions, we have to handle exceptions. Problems like syntax errors can be avoided by practicing more. For the second exception, python gives a try-except statement to handle it.

For a clearer explanation, let’s take the above situation where the divisor is 0 as an example. We capture and handle exceptions by adding a try-except statement:

def division(x, y):
	try:
		return x / y
	except ZeroDivisionError:
		print("0不能作为除数!!!")
Copy after login

Then we try calling the function in the terminal:

division(x=1, y=0)
Copy after login

Output:

0 cannot be used as a divisor! ! !

Although our input is wrong and theoretically should report an error, no error was reported and a paragraph was returned.

The following explains how the try-except statement works:

  1. The code in Try-except will be executed normally

  2. If no exception occurs, skip the except code block and end try-except

  3. If a problem exception occurs in a certain line of code in try-except, the remaining code Stop execution. If the exception that occurs is consistent with what is specified in except, the code block in except is executed. The exception handling ends and the entire application continues to execute.

  4. #If the exception that occurs is consistent with what is specified in except. does not match, then the try statement will be jumped out, the program will continue to throw exceptions and terminate the execution of the code

Of course, the code we write may have a variety of exceptions, so we can All exceptions are written in an except statement block, and the specific implementation is as follows:

except (RuntimeError, TypeError, NameError):pass
Copy after login

If any exception expression in the exception list is captured, it will enter except processing.

Of course, if you want to handle each exception individually, you can also handle it one by one:

def passpass(x=1):
	try:
		return print(x+x)
	except (RuntimeError, TypeError, NameError):
		pass
	except TypeError:
		print('参数错误啦~')
	except NameError:
		print('名称错误啦~')
Copy after login

I’ll update here today and go skipping rope tomorrow. , Hey, roll rolls every day, old Beijing chicken rolls ~ (2022.4.20)

Python’s exception types can be inherited. We only need to know here that if the exception type is specified after except Exceptions inherit from previous exceptions, so subsequent exceptions will also be caught. The example is as follows:

class A(Exception):
	pass
class B(A):
	pass
class C(B):
	pass

for cls in [A, B, C]:
	try:
		raise cls()
	except C:
		print('C')
	except B:
		print('B')
	except A:
		print('A')
Copy after login

will output:

A
B
C

On the contrary, if the order of except is reversed, only A will be output. Since exceptions B and C both inherit from A, it will terminate after catching the B exception:

class A(Exception):
	pass
class B(A):
	pass
class C(B):
	pass

for cls in [A, B, C]:
	try:
		raise cls()
	except A:
		print('A')
	except B:
		print('B')
	except C:
		print('C')
Copy after login

The output is all A:

A
A
A

If all the exceptions are extracted one by one, it will be very troublesome. At this time, you can If the exception type is not set in an except, all remaining uncaught exceptions will be caught:

def passpass(x=1):
	try:
		return print(x/x)

	except TypeError:
		print('参数错误啦~')
	except NameError:
		print('名称错误啦~')
	except:
		print('报错啦~自己查')
Copy after login

An important function: else.

The else statement is used to perform some additional operations , for example, some file operations are performed in the try code block, and resources can be released in else. The syntax format of else is as follows:

try:
	pass
except:
	pass
else:
	pass
Copy after login

Of course, we can also operate exceptions, as follows:

def passpass(x=1):
	try:
		return print(x/x)

	except TypeError as error:
		print('参数错误啦~', error)
	except NameError:
		print('名称错误啦~')
	except:
		print('报错啦~自己查')
Copy after login

Throw independently Exception

In some normal situations, developers do not make execution errors, but it does not comply with the design logic. Therefore, developers need to actively throw exceptions. At this time, we need to use the raise statement to throw exceptions:

>>> raise NameError('HiThere')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: HiThere
Copy after login

Customized exceptions

When Python’s built-in exceptions cannot meet development needs, you can customize exceptions.

自定义异常类必须要直接或间接继承自Exception类。尽管自定义异常类与其他类具有相同的功能,但为保持简洁,应该仅提高必要的属性。

class Error(Exception):
	"""Base class for exception in this module."""
	pass

class InputError(Error):
	"""Exception raised for errors in the input.

	Attributes:
		expression -- input expression in which the error occurred
		message -- explanation of the winerror

	"""
	def __init__(self, expression, message):
		self.expression = expression
		self.message = message
Copy after login

finally子句

else在代码正常执行后才会被执行的代码块,但有些情况无论代码块是否出现异常都要执行,则需要用到finally语句:

def passpass(x=1):
	try:
		return print(x/x)

	except TypeError as error:
		print('参数错误啦~', error)
	except NameError:
		print('名称错误啦~')
	except:
		print('报错啦~自己查')
	finally:
		print('运算结束~')
Copy after login

The above is the detailed content of What is the method of exception handling in Python basic tutorial?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages ​​and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

Golang vs. Python: Concurrency and Multithreading Golang vs. Python: Concurrency and Multithreading Apr 17, 2025 am 12:20 AM

Golang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.

Can visual studio code run python Can visual studio code run python Apr 15, 2025 pm 08:00 PM

VS Code not only can run Python, but also provides powerful functions, including: automatically identifying Python files after installing Python extensions, providing functions such as code completion, syntax highlighting, and debugging. Relying on the installed Python environment, extensions act as bridge connection editing and Python environment. The debugging functions include setting breakpoints, step-by-step debugging, viewing variable values, and improving debugging efficiency. The integrated terminal supports running complex commands such as unit testing and package management. Supports extended configuration and enhances features such as code formatting, analysis and version control.

See all articles