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)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1262
29
C# Tutorial
1235
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

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.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles