Python Exception handling

Source: Internet
Author: User

what is an exception? Differences between exceptions and errors error syntax errors more obvious errors can be detected during the compile code phase the effect of the exception exception that is thrown when the iteration exception occurs during code execution once an exception occurs in the program, the program will no longer continue executing How to read the wrong message L=[] l[3]    deffunc ():ImportTime Time.ti ()defMain (): Func () Main ()
The simplest exception handling L
= ['Login','Register','Exit'] forIinchEnumerate (l,1): Print(i[0],i[1])Try: Num= Int (Input ('Num:')) Print(l[num-1])exceptIndexerror:Print('Please enter a number') Multi-branch exception handling L= ['Login','Register','Exit'] forIinchEnumerate (l,1): Print(i[0],i[1])Try: Num= Int (Input ('Num:')) Print(l[num-1])exceptValueError:Print('Please enter a number')exceptIndexerror:Print('the number you entered is not valid') Universal ExceptionTry: Name#NameerrorDIC ={} dic['Key']exceptException as variable name:#exception the parent class for all exceptions Print(Type (variable name), variable name, variable name.__traceback__. Tb_lineno) Universal anomalies and other branches of cooperation: the universal anomaly will always be at the end of all except .Try: name []3] ImportaexceptNameerror:PassexceptIndexerror:PassexceptException:Passother mechanisms for exception handlingTry: name []3]exceptIndexerror:Print('Index Error')exceptNameerror:Print('Name Error')Try: name []3]except(Indexerror,nameerror) as E:Print(e)Try: A= 1#name #[][3]exceptNameerror:Print('Name Error')exceptException:Print('Universal Anomaly')Else:#Code in try executes code in else when no exception is executed Print('do else.')finally:#do the work of operating system resources return anyway Print('the execution finally')Try: F= Open ('file','W') #F.read ()exit ()except:Pass #Complex Logicfinally: F.close ()Print('execute me.')deffunc ():Try: F= Open ('file','W') returnF.read ()finally: F.close ()Print('I'm done.') func ()Try/exceptTry/except/ElseTry/except/Else/finallyTry/except/finallyTry/finallyActive Throw ExceptionTry: Num= Int (Input ('>>>'))exceptException:Print('do something after an exception and let it throw an exception') Raise #An exception that occurs in a try statement that is thrown unchangedCustom ExceptionsRaiseNameerror ('this is an exception to the name error')classevaexception (Exception):def __init__(self,msg): Self.msg=msgRaiseEvaexception ('This is a what what what wrong and what 's the problem') AssertionassertBoolean valueassertTrueifFalse:Print(1234234)Else: RaiseAssertionerror considerations for using exception handling assertionsassert RaiseException handling for active throw exceptionsTry/except Try/except/Else Try/except/Else/finally Try/except/finally Try/finallystrat.pyif __name__=='__main__': Try: Core.main ()exceptException:Passminimizing the use of exception handling can be avoided by the logic of the code to avoid the logic should be to a certain sentence/A few words to deal with and finally add a large exception handling to the outer layer

Python Exception handling

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.