Exception Handling in Python-exception and python-Exception

Source: Internet
Author: User

Exception Handling in Python-exception and python-Exception

When writing a python program, do not be afraid to report errors, or be afraid that your English is not good enough. Do not read Red words in your mind. in fact, the error is also a routine for you to find ~ Only when the exception type is identified can the right remedy be taken.

Common exceptions:

ExceptionAll abnormal base classes

AttributeErrorProperty application or value assignment failure

IOErrorThis is triggered when you try to open a non-existent file.

IndexErrorThis parameter is triggered when an index does not exist in the sequence is used.

KeyErrorThis parameter is triggered when a key that does not exist in the ing is used.

NameErrorIf the name (variable) is not found

SyntaxErrorTriggered when the code is in the wrong format

TypeErrorWhen an internal creation operation or function is applied to an object of the error type

ValueErrorThe internal creation operation or function is applied to objects of the correct type.

ZeroDivisionErrorThis parameter is triggered when the second parameter of the division or division operation is 0.

 

1. Throw an exception

def div(x,y):    if y == 0:        raise ZeroDivisionError('Zero is not allowed.')    return x/ytry:    div(4,0)except Exception as e:    print(e)
Zero is not allowed.Process finished with exit code 0

 

2.Capture exceptions:
Multiple exceptions can be captured at the same time, exception objects can be captured, and exception types can be ignored to capture all exceptions

Try: x = int (input ('input x: ') y = int (input ('input y:') print ('x/y = ', x/y) except t ZeroDivisionError: # Catch print ("ZeroDivision") except 0 exception T (TypeError, ValueError) as e: # Catch multiple exceptions, print (e) The exception object output T: # capture other types of exceptions print ("it's still wrong ")
input x:3input y:0ZeroDivisionProcess finished with exit code 0
input x:5input y:ainvalid literal for int() with base 10: 'a'Process finished with exit code 0

Try/try t can be addedElseStatement to implement what to execute when there is no exception

Try: x = int (input ('input x: ') y = int (input ('input y:') print ('x/y = ', x/y) except t ZeroDivisionError: # Catch print ("ZeroDivision") except 0 exception T (TypeError, ValueError) as e: # Catch multiple exceptions, print (e) failed T: # capture other types of exceptions print ("it's still wrong") else: # print ('It works Well') When no exception occurs ')
input x:4input y:2x/y =  2.0it works wellProcess finished with exit code 0

3.Finally statement
Whether or not an exception occurs, finally statement block content will be executed at last for cleanup.
Therefore, you can close the file in the finally statement to ensure that the file can be closed normally.

Try: x = int (input ('input x: ') y = int (input ('input y:') print ('x/y = ', x/y) except t ZeroDivisionError: # Catch print ("ZeroDivision") except 0 exception T (TypeError, ValueError) as e: # Catch multiple exceptions, print (e) failed T: # capture other types of exceptions print ("it's still wrong") else: # print ('It works Well') finally: # print ("Cleaning up") is executed no matter whether an exception exists ")
input x:4input y:ainvalid literal for int() with base 10: 'a'Cleaning upProcess finished with exit code 0

After an exception is thrown, if it is not received, the program will throw it to the previous layer. For example, if the function call is still not received, it will continue to throw, if the program does not handle this exception at the end, it will be thrown to the operating system-your program crashes.

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.