==> exception handling of Python learning

Source: Internet
Author: User
Tags sql error

First, why do you want to do exception handling

In the process of running the program, you may encounter a variety of errors, the program once an error, will stop running. In order for the program to run properly, it is necessary to catch the exception, by the corresponding processing of the caught exception, to ensure the normal operation of the program.

Second, catch all anomalies

1. Try: Catch the exception of this code

2. Except Exception: Catch all anomalies

3, Else: Execute the ELSE code if there is no error, but else do not write can

4, finally: regardless of whether there is an exception, will execute finally the following code, it can also not write

1 #Exception Handling2First = input ('First :')3Second = input ('Second:')4 Try:#Catching exceptions5First =Int (first)6Second =Int (second)7res = first/Second8 exceptException as E:#try inside this code out of the way when the exception goes9     Print(e)Ten     Print('something went wrong.') One Else:#no mistakes, no need to write. A     Print('No Errors')#go when there's nothing wrong -     Print(RES) - finally:#it doesn't have to be written, whether it's an error or not. the     Print('This code will be executed whether or not an error occurs! ')

Third, catch the abnormal exercise: perfect MySQL operation function

1 defmy_db (SQL):2     ImportPymysql3     Try:4conn = Pymysql.connect (* *mysql_info)5     exceptException as E:6         Print('Database connection Failed')7         return 'Database connection Failed'  #end of return function encountered8     Else:#continue execution without error9Cur =conn.cursor ()Ten         Try: One cur.execute (SQL) A         exceptException as Res: -             Print('error executing SQL, SQL is:%s'%sql) -         Else:#continue execution without error the             ifSql.strip (). Split () [0].upper () = ='SELECT': -res =Cur.fetchall () -             Else: - Conn.commit () +res ='OK' -         finally:#This finally corresponds to the execution of a SQL error try, the previous connection failure directly out of the function + cur.close () A conn.close () at         returnRes

Iv. Common anomalies

1 Attributeerror: An attempt was made to access a property that an object does not have, such as foo.x, but Foo has no attribute x2IOError: Input/output exception, generally cannot open file3 Importerror: Unable to import module or package, usually path problem or name error4 Indentationerror: Code not aligned correctly, syntax error5Indexerror: The subscript index exceeds the sequence boundary, such as X has only three elements, but attempts to access the X[3]6 Keyerror: Attempting to access a key that does not exist in the dictionary7Keyboardinterrupt:ctrl +C is pressed8 nameerror: Using a variable that has not been assigned to an object9 syntaxerror: Syntax errorTen TypeError: The Incoming object type does not match the requirements One Unboundlocalerror: Attempts to access a local variable that is not yet set, typically because there is another variable with the same name outside of the code block AValueError: Pass in a value that is not expected by the caller, even if the value is of the correct type

V. Actively throwing exceptions

Let it automatically throw an exception in the code, and then snap to it. For example, when we write automated test scripts, the results do not match the expectations, we can actively throw an exception, and then catch to do other processing. Actively throws an exception using the Raise keyword.

1 Try : 2     Raise Keyerror  #  proactively throws a Keyerror exception 3except  keyerror as E:4      Print(' This is an unsolicited exception ')

==> exception handling of Python learning

Related Article

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.