How to handle python exceptions

Source: Internet
Author: User
This article describes how to handle python exceptions.

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 is to make the program more executable and run smoothly. at the same time, users are not allowed to see embarrassing error messages. In other words, 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

In python3, try statements are provided to handle exceptions. the format is:

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 ')
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)

When you want to handle multiple exceptions, you can write as follows:

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

Although exceptions can capture arbitrary exceptions, you must first define exceptions for special processing or reminder, 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 shown below:

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) to customize the 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. msg try: raise Myerror ('error') failed t Exception as f: print (f)

The above is a detailed explanation of the python exception handling method. For more information, see other related articles in the first PHP community!

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.