Python uses exception objects to represent exceptions. When an error is encountered, an exception is thrown. If the exception object is not handled or caught, the program will terminate execution with a so-called traceback (an error message):
>>> 1/0
Traceback (most recent call last):
File "
1/0
ZeroDivisionError: integer division or modulo by zero
raise statement
To raise an exception, you can call raise with a class (a subclass of Exception) or an instance parameter number statement. The following example uses the built-in Exception class:
>>> raise Exception #引发一个没有任何错误信息的普通异常 Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> raise Exception Exception >>> raise Exception('hyperdrive overload') # 添加了一些异常错误信息 Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> raise Exception('hyperdrive overload') Exception: hyperdrive overload
The built-in exception class that comes with the system:
>>> import exceptions
>>> dir(exceptions)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'EnvironmentError', 'Exception', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError ', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TypeError', 'UnboundLocalError ', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__doc__', '__name__', '__package__']
Wow! There are many commonly used built-in exception classes:
Custom exception
Although the built-in exception classes have covered most situations and are sufficient for many requirements, sometimes you still need to create your own exception class.
Same as other common classes - just make sure to inherit from the Exception class, whether directly or indirectly. Like the following:
>>> class someCustomExcetion(Exception):pass
Of course, you can also add some methods to this class.
Catch exceptions
We can use try/except to implement exception catching and processing.
Suppose you create a program that allows the user to enter two numbers and then divide them:
x = input('Enter the first number: ') y = input('Enter the second number: ') print x/y #运行并且输入 Enter the first number: 10 Enter the second number: 0 Traceback (most recent call last): File "I:/Python27/yichang", line 3, in <module> print x/y ZeroDivisionError: integer division or modulo by zero 为了捕捉异常并做出一些错误处理,可以这样写: try: x = input('Enter the first number: ') y = input('Enter the second number: ') print x/y except ZeroDivisionError: print "输入的数字不能为0!" #再来运行 >>> Enter the first number: 10 Enter the second number: 0
The entered number cannot be 0! #How about it? This time it is much more friendly
It would be better if we raise an exception during debugging. If we do not want the user to see the exception information during the interaction with the user. How to turn on/off the "blocking" mechanism?
class MuffledCalulator: muffled = False #这里默认关闭屏蔽 def calc(self,expr): try: return eval(expr) except ZeroDivisionError: if self.muffled: print 'Divsion by zero is illagal' else: raise #运行程序: >>> calculator = MuffledCalulator() >>> calculator.calc('10/2') 5 >>> calculator.clac('10/0') Traceback (most recent call last): File "<pyshell#30>", line 1, in <module> calculator.clac('10/0') AttributeError: MuffledCalulator instance has no attribute 'clac' #异常信息被输出了 >>> calculator.muffled = True #现在打开屏蔽 >>> calculator.calc('10/0') Divsion by zero is illagal
Multiple except clauses
If you run the above program (enter two numbers and calculate division) and enter the content above, another exception will be generated:
try: x = input('Enter the first number: ') y = input('Enter the second number: ') print x/y except ZeroDivisionError: print "输入的数字不能为0!" #运行输入: >>> Enter the first number: 10 Enter the second number: 'hello.word' #输入非数字 Traceback (most recent call last): File "I:\Python27\yichang", line 4, in <module> print x/y TypeError: unsupported operand type(s) for /: 'int' and 'str' #又报出了别的异常信息
Okay! We can add an exception handler to handle this situation:
try: x = input('Enter the first number: ') y = input('Enter the second number: ') print x/y except ZeroDivisionError: print "输入的数字不能为0!" except TypeError: # 对字符的异常处理 print "请输入数字!" #再来运行: >>> Enter the first number: 10 Enter the second number: 'hello,word'
Please enter a number!
One block to catch multiple exceptions
Of course we can also use one block to catch multiple exceptions:
try: x = input('Enter the first number: ') y = input('Enter the second number: ') print x/y except (ZeroDivisionError,TypeError,NameError): print "你的数字不对!
"
Catch all exceptions
Even if the program handles several exceptions, such as the above After running the program, what if I enter the following content
>>> Enter the first number: 10 Enter the second number: #不输入任何内容,回车 Traceback (most recent call last): File "I:\Python27\yichang", line 3, in <module> y = input('Enter the second number: ') File "<string>", line 0 ^ SyntaxError: unexpected EOF while parsing
faint~! What should I do? There are always situations that we accidentally ignore. If we really want to use a piece of code to catch all exceptions, Then you can ignore all exception classes in the except clause:
try: x = input('Enter the first number: ') y = input('Enter the second number: ') print x/y except: print '有错误发生了!' #再来输入一些内容看看 >>> Enter the first number: 'hello' * )0
An error occurred!
End
Don’t worry! Let’s talk about the last situation, okay, the user accidentally entered the wrong one. Information, can you give me another chance to enter? We can add a loop to ensure that it ends when you lose:
while True: try: x = input('Enter the first number: ') y = input('Enter the second number: ') value = x/y print 'x/y is',value except: print '列效输入,再来一次!' #运行 >>> Enter the first number: 10 Enter the second number: 列效输入,再来一次! Enter the first number: 10 Enter the second number: 'hello' 列效输入,再来一次! Enter the first number: 10 Enter the second number: 2 x/y is 5

Arraysarebetterforelement-wiseoperationsduetofasteraccessandoptimizedimplementations.1)Arrayshavecontiguousmemoryfordirectaccess,enhancingperformance.2)Listsareflexiblebutslowerduetopotentialdynamicresizing.3)Forlargedatasets,arrays,especiallywithlib

Mathematical operations of the entire array in NumPy can be efficiently implemented through vectorized operations. 1) Use simple operators such as addition (arr 2) to perform operations on arrays. 2) NumPy uses the underlying C language library, which improves the computing speed. 3) You can perform complex operations such as multiplication, division, and exponents. 4) Pay attention to broadcast operations to ensure that the array shape is compatible. 5) Using NumPy functions such as np.sum() can significantly improve performance.

In Python, there are two main methods for inserting elements into a list: 1) Using the insert(index, value) method, you can insert elements at the specified index, but inserting at the beginning of a large list is inefficient; 2) Using the append(value) method, add elements at the end of the list, which is highly efficient. For large lists, it is recommended to use append() or consider using deque or NumPy arrays to optimize performance.

TomakeaPythonscriptexecutableonbothUnixandWindows:1)Addashebangline(#!/usr/bin/envpython3)andusechmod xtomakeitexecutableonUnix.2)OnWindows,ensurePythonisinstalledandassociatedwith.pyfiles,oruseabatchfile(run.bat)torunthescript.

When encountering a "commandnotfound" error, the following points should be checked: 1. Confirm that the script exists and the path is correct; 2. Check file permissions and use chmod to add execution permissions if necessary; 3. Make sure the script interpreter is installed and in PATH; 4. Verify that the shebang line at the beginning of the script is correct. Doing so can effectively solve the script operation problem and ensure the coding process is smooth.

Arraysaregenerallymorememory-efficientthanlistsforstoringnumericaldataduetotheirfixed-sizenatureanddirectmemoryaccess.1)Arraysstoreelementsinacontiguousblock,reducingoverheadfrompointersormetadata.2)Lists,oftenimplementedasdynamicarraysorlinkedstruct

ToconvertaPythonlisttoanarray,usethearraymodule:1)Importthearraymodule,2)Createalist,3)Usearray(typecode,list)toconvertit,specifyingthetypecodelike'i'forintegers.Thisconversionoptimizesmemoryusageforhomogeneousdata,enhancingperformanceinnumericalcomp

Python lists can store different types of data. The example list contains integers, strings, floating point numbers, booleans, nested lists, and dictionaries. List flexibility is valuable in data processing and prototyping, but it needs to be used with caution to ensure the readability and maintainability of the code.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Linux new version
SublimeText3 Linux latest version

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Notepad++7.3.1
Easy-to-use and free code editor
