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

WBOY
Release: 2023-05-27 21:24:52
forward
1550 people have browsed it

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 "", 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 "", line 1, in 
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 "", line 1, in 
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!

Related labels:
source:yisu.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!