错误和异常概念
错误:
1.语法错误:代码不符合解释器或者编译器语法
2.逻辑错误:不完整或者不合法输入或者计算出现问题
异常:执行过程中出现万体导致程序无法执行
1.程序遇到逻辑或者算法问题
2.运行过程中计算机错误(内存不够或者IO错误)
错误和异常区别
错误:
代码运行前的语法或者逻辑错误,
语法错误在执行前修改,逻辑错误无法修改
异常分为两个步骤:
1.异常产生,检查到错误且解释器认为是异常,抛出异常;
2.异常处理,截获异常,忽略或者终止程序处理异常
Python常见错误
常见错误:ipython下
1. a : NameError
在没有定义一个变量的时候直接引用
2. if True : SyntaxError
语法错误
3. f = open('1.txt') : IOError
试图打开一个不存在的文件的时候
4. 10/0 : ZeroDivisionError
5. a = int('dd') : ValueError
进行强制类型转换的时候遇到的错误
try--except异常处理(1)
try-except:异常处理
try: try_suite except Exception [, e]: exception_block
1.try用来捕获try_suite中的错误,并且将错误交给except处理
2.except用来处理异常,如果异常处理和设置捕获异常一致,使用exception_block处理异常
例:
try: a except Exception, e: print e
try-except捕获异常分析:
Case 1:
try: undef except: print 'catch an except'
Case 2:
try: if undef except: print 'catch an except'
case 1:可以捕获异常,因为是运行时错误
case 2:不能捕获异常,因为是语法错误,运行前错误
Case 3:
try: undef except NameError, e: print 'catch an except', e Case 4: try: undef except IOError, e: print 'catch an except', e
case 3:可以捕获异常,因为设置捕获NameError异常
case 4:不能捕获异常,因为设置IOError,不会处理NameError
try--except异常处理(2)
try-except:处理多个异常
try: try_suite except Exception1 [e]: exception_block1 except Exception2 [e]: exception_block2 except ExceptionN [e]: exception_blockN
try-except--else使用
try: try_suite except Exception1 [e]: exception_block1 else: none_exception
如果没有异常,执行else语句中的代码
try--finally语句
try-finally语句:
try: try_suite finally: do_finally
1.如果try语句没有捕获错误,代码执行do_finally语句
2.如果try语句捕获错误,程序首先执行do_finally语句,然后将捕获到的错误交给python解释器处理
try-finally语句:
规则:try-finally无论是否检测到异常,都会执行finally代码
作用:为异常处理事件提供清理机制,用来关闭文件或者释放系统资源
try-except-finally使用:
try: try_suite except: do_except finally: do_finally
1.若try语句没有捕获异常,执行完try代码段后,执行finally
2.若try捕获异常,首先执行except处理错误,然后执行finally
try-except-else-finally使用:
try: try_suite except: do_except else: do_else finally: do_finally
1.若try语句没有捕获异常,执行完try代码块后,执行else代码块,最后执行finally
2.若try捕获异常,首先执行except处理错误,然后执行finally
with语句
with语句:
with context [as var]:
with_suite
1.with语句用来代替try-except-finally语句,是代码更加简洁;
2.context表达式返回是一个对象;
3.var用来保存context返回对象,单个返回值或者元祖;
4.with_suite使用var变量来对context返回对象进行操作
……
raise和assert
raise语句
raise语句用于主动抛出异常
语法格式:raise [exception [, args]]
exception: 异常类
args: 描述异常信息的元组
例:
raise TypeError raise TypeError, 'Test Error' raise IOError, 'File Not Exist'
assert语句
断言语句:assert语句用于检测表达式是否为真,如果为假,引发AssertionError错误;
语法格式:assert expression [, args]
expression:表达式
args:判断条件的描述信息
例:
assert 7==6 assert 0, 'Test Error'
Python标准和自定义异常
标准异常:python内建异常,程序执行前就已经存在
自定义异常:
1.python允许自定义异常,用于描述python中没有涉及的异常情况
2.自定义异常必须继承Exception类
3.自定义异常只能主动触发
自定义异常示例:
class FileError(IOError): pass raise FileError, 'Test FileError' class CustomError(Exception): def __init__(self, info): Exception.__init__(self) self.errorinfo = info def __str__(self): return 'CustomError: %s' % self.errorinfo try: raise CustomError('test CustomError') except CustomError, e: print 'Error Info : %s' % e
相关推荐:《Python教程》
Atas ialah kandungan terperinci python异常与错误区别. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Sebab -sebab mengapa skrip Python tidak dapat dijalankan pada sistem Unix termasuk: 1) kebenaran yang tidak mencukupi, menggunakan chmod xyour_script.py untuk memberikan kebenaran pelaksanaan; 2) garis shebang yang tidak betul atau hilang, anda harus menggunakan #!/Usr/bin/envpython; 3) tetapan pembolehubah persekitaran yang salah, anda boleh mencetak debugging os.environ; 4) Menggunakan versi Python yang salah, anda boleh menentukan versi pada garis Shebang atau baris arahan; 5) masalah pergantungan, menggunakan persekitaran maya untuk mengasingkan ketergantungan; 6) Kesalahan sintaks, gunakan python-mpy_compileyour_script.py untuk mengesan.

Menggunakan tatasusunan python lebih sesuai untuk memproses sejumlah besar data berangka daripada senarai. 1) Array menjimatkan lebih banyak memori, 2) array lebih cepat untuk beroperasi dengan nilai berangka, 3) Arrays Force Jenis Konsistensi, 4) Array bersesuaian dengan array C, tetapi tidak fleksibel dan mudah seperti senarai.

Listsare yang lebih baik lebih baik foreflexibilityandmixdatatatypes, whilearraysares sand sumerical sand sand sand lared datasets.1) Senarai yang tidak dapat diselaraskan xibility, mixeddatatypes, dan elementChanges.2) Operasi sensori UsArray, LargedataSet, dan WhenmememoryefficyFiciency.2

NumpyManagesMemoryforlargeArraySefficientlyusingViews, salinan, danMemory-mappedfiles.1) viewSallowSlicingWithoutCopying, secara langsungModifyingTheoriginalArray.2) copiescanbecreatedwithTheCopy () methorpreserveservervesvesverdata.3) MemoriSberServervesvesves

Listsinpythondonotrequireimportingamodule, whilearraysfromthearraymoduledoneedanimport.1) listsarebuilt-in, serba boleh, dancanholdmixeddatatypes.2) arraysaremorememory-efficientfornumericydatabuTabeSflexible, yang tidak dapat dilupakan.

Pythonlistscanstoreanydatatype, arraymoduleArraysstoreonetype, andnumpyarraysarefornumumericalcomputations.1) listsareversatileButlessMememory-efficient.2) arraymoduleArduleArrayRaysarememory-efficientforhomogenhomogenhomogenhomogenhomogenhomogenhomogenhomogenhomogenhomogenhomogenhomogenhomogenhomogenhomogenhomogen

KetikayyoUttemptToStoreAveFheWrongatatypeinapythonArray, anda akan menjadicounteratypeerror

Pythonlistsarepartofthestandardlibrary, sementara


Alat AI Hot

Undresser.AI Undress
Apl berkuasa AI untuk mencipta foto bogel yang realistik

AI Clothes Remover
Alat AI dalam talian untuk mengeluarkan pakaian daripada foto.

Undress AI Tool
Gambar buka pakaian secara percuma

Clothoff.io
Penyingkiran pakaian AI

Video Face Swap
Tukar muka dalam mana-mana video dengan mudah menggunakan alat tukar muka AI percuma kami!

Artikel Panas

Alat panas

Notepad++7.3.1
Editor kod yang mudah digunakan dan percuma

ZendStudio 13.5.1 Mac
Persekitaran pembangunan bersepadu PHP yang berkuasa

SublimeText3 versi Cina
Versi Cina, sangat mudah digunakan

SublimeText3 versi Mac
Perisian penyuntingan kod peringkat Tuhan (SublimeText3)

SublimeText3 Linux versi baharu
SublimeText3 Linux versi terkini
