Python Exception handling

Source: Internet
Author: User
Tags builtin throw exception

Exception HandlingErrors and Exceptions
    • Error: Syntax issues before the program is run, such as: keywords, indents, parentheses not equal

    • Exceptions: Errors that occur during the execution of a program, such as: variable undefined, divisor 0, attribute not present, etc.

Exception Handling
  • Description: Exception handling can be considered as a special Process Control statement, which can improve the robustness of the code.

  • Syntax: try-except

    try: 
       print ( Normal execution ')
       # print (a)
        Print (3/0)
    except exception as e:
       # exception is the base class for all exceptions, so you can catch all exceptions here
       print ( ' exception, processing ')
       print (e)
    ?
    print ( ' other code ')
  • To capture multiple exceptions:

    Try
    # Print (a)
    # Print (3/0)
    FP =Open' 123.txt ')
    except nameerror as e:
       print ( ' nameerror: ', Span class= "cm-variable" >e)
    except zerodivisionerror as e:
       print ( Span class= "cm-string" > ' zerodivisionerror: ', e)
    Except exception as e:
       print ( ' other: ', e)

    can also be used to group multiple exceptions:

     
    try:
       # print (a)
       # print (3/0)
       FP = open ( ' 123.txt ')
    except (nameerror, zerodivisionerror) as e:
       # uniformly handle certain exceptions, Write to tuple
       print (e)
    except:
       print ( ' other exceptions ')
  • else and finally

     
    try:
       print (    print (a)
    except:
        print ( ' exception ')
    else:
       # an exception is not performed
       print ( finally:
        # any error exception will execute
       print (

    ELSE: When no exception occurs, the exception is executed.

    Finally: Regardless of whether there is an exception, it will execute

  • Throw exception: Raise

     
    try:
       print (    # according to the needs of the code logic, Manually throwing a specific exception
       raise exception ( ' manual throw exception ')
       print ( ' all OK ')
    except exception as e:
       print ( "exception occurred: ', e)
    ?
    print ( ' end ')
  • Exception nesting: nested try-except structures in try-except structures


    Print' I'm going to work, nothing can stop me from working '
    Try
    Print' I'm going to ride an electric car ')
    RaiseException (The wicked guy pulled my charger out last night and couldn't ride a bike.
    Print' Ride the electric car early to reach the company ')
    ExceptExceptionAsE:
    PrintE
    Try
    Print' I'm going to take the bus ')
           raise exception (" waited 20 minutes without a bus, decisively giving up ')
           print (" take the bus on time to reach the company ')
       except Exception as e:
           print (e)
           print ( I'm going to take a taxi)
           print (" taxi or fast, a few will be to the company ')
    ?
    print ( ' enthusiastic start of the day's work ')
  • Custom Exception class: base class to inherit from Exception (Exception)


    # Custom Exception class, names usually end with exception
    ClassMyException (Exception):
    Def__INIT__ (SelfMSG):
    Self.msg =Msg
    ?
    Def__STR__ (Self):
    # repr key variable is converted to a string, if itself is a string is not necessary
    # return repr (self.msg)
    ReturnSelf.Msg
    ?
       def deal (self):
           print ( ' exception handled ')
    ?
    try:
       print (    raise myexception ( ' manual throw definition exception ')
    except myexception as e:
       print (e)
       e.deal ()
  • Special use

      • Scene: When doing the file operation, whether read or write in the middle, or whether the error is abnormal, finally must close the file

      • With: using with, there is no need to close the file, the WITH statement block will ensure that the file is closed.


    # fp = open (' Test.txt ', ' RB ')
    # various read and write operations
    # Fp.close ()
    ?
    # using with, no need to worry about file closing issues
    Open (fp:
    FP.Read (5)
    Print (content)

    ?

Python Exception handling

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.