[Python collection] Exception Handling and python collection Exception Handling

Source: Internet
Author: User

[Python collection] Exception Handling and python collection Exception Handling
Exception

Exceptions are taken out of the normal control flow due to exceptions, exceptions, and errors of the program. They are generally divided into the following two phases:

 

1. Exception: an error is printed out after it occurs, which is called an unhandled exception. The default process is to automatically output some debugging information and terminate the program running.

2. Exception Handling: if the Code explicitly handles exceptions, the program will not terminate the operation and improve the program's fault tolerance.

To put it bluntly, the purpose of exception handling isIn order to make the program more executable and run smoothlyAnd Prevent Users From seeing embarrassing error messages,In general, users are not allowed to see the yellow pages.

You can view the Exception through the Exception type in python3.

Common exceptions:

AttributeError # try to access a tree that does not exist in an object, such as foo. x, but foo has no attribute xIOError # input/output exception; basically, the file ImportError cannot be opened # The module or package cannot be introduced; basically, it is a path problem or name error. IndentationError # syntax error (subclass). The Code does not correctly align IndexError # The subscript index exceeds the sequence boundary. For example, if x has only three elements, but try to access x [5] KeyError # try to access the key KeyboardInterrupt that does not exist in the dictionary # Ctrl + C is pressed NameError # Use the variable SyntaxError # The Python code is invalid, code cannot be compiled (I personally think this is a syntax error and I wrote an error) TypeError # The type and requirement of the input object do not conform to UnboundLocalError # try to access a local variable that has not been set yet, basically, because there is another global variable with the same name, you think you are accessing it ValueError # Passing in a value that the caller does not expect, even if the value type is correct

More exceptions:

ArithmeticErrorAssertionErrorAttributeErrorBaseExceptionBufferErrorBytesWarningDeprecationWarningEnvironmentErrorEOFErrorExceptionFloatingPointErrorFutureWarningGeneratorExitImportErrorImportWarningIndentationErrorIndexErrorIOErrorKeyboardInterruptKeyErrorLookupErrorMemoryErrorNameErrorNotImplementedErrorOSErrorOverflowErrorPendingDeprecationWarningReferenceErrorRuntimeErrorRuntimeWarningStandardErrorStopIterationSyntaxErrorSyntaxWarningSystemErrorSystemExitTabErrorTypeErrorUnboundLocalErrorUnicodeDecodeErrorUnicodeEncodeErrorUnicodeErrorUnicodeTranslateErrorUnicodeWarningUserWarningValueErrorWarningZeroDivisionError
Exception Handling

Try statement in python3 to handle exceptions, Format:

Try: print ('# Run the code that is not specified first') failed t Exception as e: # All exceptions are inherited to the Exception class and can catch any exceptions. print (e) # You can obtain the error e print ('# If an exception occurs, execute the exception handler') else: print ('# If no exception occurs in the main code block and the execution is complete, continue to execute ')

Or:

Try: print ('# Run the specific code first') failed t Exception as e: print ('# Catch the corresponding Exception and handle it') finally: print ('# execute whatever the exception or not ')

Of course, the try statement can also capture specific exceptions.But not the specified exception. For more information, see the following examples:

dic = ["English", 'Chinese']try:    dic[10]except IndexError as e:    print(e)
s1 = 'hello'try:    int(s1)except ValueError as e:    print(e)

If an unspecified exception occurs, an error is returned.:

# If no exception is caught, the program directly reports an error s1 = 'hello' try: int (s1) failed t IndexError as e: print (e)

This can also be written when you want to handle multiple exceptions.:

T (AttributeError, NameError) as e: print (e) print ('# This is the syntax for capturing multiple types of exceptions ')

Although exceptions can capture arbitrary exceptionsFor special handling or reminder exceptions, you must first define and finally define exceptions to ensure the normal operation of the program.Therefore, this method is also frequently used:

S1 = 'hello' try: int (s1) failed t KeyError as e: print ('key error') failed t IndexError as e: print ('index error') failed t Exception as e: print ('error ')

The raise statement actively triggers an exception,In python3, you can use the raise statement to throw a general Exception type (Exception), as follows:

Try: raise Exception ('error... ') # This is an Exception that is triggered automatically. Failed t Exception as e: print (e)

In python3, you can also create a class that inherits to the general Exception type (Exception ).Custom exception:

# For raise statements, also include: class Myerror (Exception): def _ init _ (self, msg): self. msg = msg def _ str _ (self): # output return self in string format. msgtry: raise Myerror ('error') failed t Exception as f: print (f)

You can also use the with statement to simplify the code, which is often used in file processing. For details, see [python collection] File Operations.

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.