Exceptions to Python's learning notes

Source: Internet
Author: User
Tags stack trace

Python uses an exception object to represent the exception, and if the exception object is not processed or snapped, the program will backtrack (traceback) execution.

Exceptions can be raised automatically when an error occurs, or they can be raised proactively.

If the exception is thrown, it is propagated to the program call where it is not processed, until the main program (global scope), and if the main program still has no exception handling, the program terminates with a stack trace.

Raise: Throwing an exception

Raise Exceptiontraceback (most recent):   " <pyshell#1> "  in <module>    raise  exceptionexception

>>> Raise Exception ("Error!!!")
Traceback (most recent):
File "<pyshell#2>", line 1, in <module>
Raise Exception ("Error!!!")
Exception:error!!!

Common built-in exception classes:

Class name Describe
Exception base class for all exceptions
Attributeerror Thrown when an attribute reference or assignment fails
IOError Thrown when an attempt is made to open a file that does not exist (including other conditions)
Indexerror Thrown when using an index that does not exist in the sequence
Keyerror Thrown using a key that does not exist in the map
Nameerror Thrown when a name (variable) cannot be found
SyntaxError Thrown when the code is in the wrong form
TypeError Object raised in the built-in operation or function applied to the wrong type
ValueError The built-in operation or function is applied to the correct object, but the object uses an inappropriate value to raise the
Zerodivision The second argument of the division or modulo-division operation is a 0 o'clock throw

Custom exception class: Inherit from exception

class Defexception (Exception):Pass

Catching exceptions: Using the Try/except statement implementation >>> try:

    =  int (input ("the firstnum:"))    = Int (input ("thesecond Num:"))    print(x/y)except  Zerodivisionerror:    print("Error") the first    num :5 Thesecond num:0
Error
>>>Try: x= Int (Input ("The first num:")) Y= Int (Input ("The second num:"))    Print(x/y)exceptZerodivisionerror:Print("Error")exceptValueError:Print("TypeError") The first num:5The second Num:otypeerror

Catch multiple exceptions with one block:

Try :     =  int (input ("the firstnum:"))    = Int (input ("thesecond Num:"))    print(x/y)except  ( Zerodivisionerror,valueerror):    print("Error") The first    num:5 Thesecond Num:0error

Snapping objects:

Try :     =  int (input ("the firstnum:"))    = Int (input ("thesecond Num:"))    print(x/y)except  ( Zerodivisionerror,valueerror) as E:    print(e) The first    num:5 Thesecond Num:0division by Zero

Catch all Exceptions:

Try :     = Int (Input ("the firstnum:"))    = Int (input ("Thesecond num:  "))    print(x/y)except:      Print("some errors") the first num:5 Thesecond num:some errors 

This approach captures the user's attempt to abort execution and hides any errors that programmers have not thought of and are unprepared for.

To handle exception cases:

#loop when the input is not valid until the legal value exits the loop whileTrue:Try: x= Int (Input ("The first num:")) Y= Int (Input ("The second num:"))        Print(x/y)except:        Print("Error")    Else:         Break#Run ResultsThe first num:5The second num:0errorthe first num:6The second num:32.0

Finally clause: Cleans after possible exceptions, regardless of whether any exceptions are performed. In the same try statement, it cannot be used with except.

x =NoneTry: x= 1/0finally:    Print("Cleaning")    delx#ResultsCleaningtraceback (most recent): File"input.py", Line 4,inch<module>x= 1/0zerodivisionerror:division by ZeroRepl closed***

You can combine try,except,else,finally in one statement

Try :     = 1/0Else:    print("done")  Finally:    print("cleaning")#  Running results cleaning***repl closed***

Exceptions to Python's learning notes

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.