Day7 Exception Handling and php7 Exception Handling

Source: Internet
Author: User

Day7 Exception Handling and php7 Exception Handling

Exception Handling

The following is a simple example:

Data = {} try: data ["name"] failed t KeyError as e: # e is the incorrect trust information. The cause of the error is print ("No such key", e)
The running result is as follows:
No such key 'name'

We can see from the above results that when an error occurs, we can use try... handle T to avoid the error and prevent the program from reporting the error. Can continue to run. Here, as e is the details of the error and the cause.

Methods To catch multiple errors: (1)

Data = {} try: data ["name"] failed t KeyError as e: # e is the incorrect trust information. The cause of the error is print ("No such key", e) failed t IndexError as e: print ("List Index error", e)

Methods To catch multiple errors: (2)

Data = {} names = [] try: names [1] cannot T (IndexError, KeyError) as e: # e is the incorrect trust information, cause of error print ("List Index error", e)

Put multiple error causes into the element and automatically search for errors of the term.

Exception capture is basically all errors, which are not recommended in General cases. If they are used at the end of the process, they will be crawled for the last time when none of the above errors are captured.

Exception

Try:

Code

Except T (Error1, Error2) as e:

Print (e)

Failed t Exception: capture all errors. It is generally not recommended. It should be placed on the last capture. As follows:

Data = {} names = [] num = 1try: num/0 handle T (IndexError, KeyError) as e: # e is the incorrect trust information, cause of error print ("List Index error", e) failed t FileNotFoundError as e: print ("file does not exist", e) failed t Exception as e: print ("Unknown error ", e)
The running result is as follows:
Unknown error division by zero

In the code above, the handle T Exception is used to handle all the above situations that cannot capture errors. It is often executed when all efforts fail.

Next, let's take a look at the unit test. We often test the Code. If an error occurs in execution and no error occurs, let us know that there is no problem, as shown in the following code test:

Data = {} names = [] num = 1try: num/0 handle T (IndexError, KeyError) as e: # e is the incorrect trust information, cause of error print ("List Index error", e) failed t FileNotFoundError as e: print ("file does not exist", e) failed t Exception as e: print ("Unknown error ", e) else: print ("everything is OK ")
The running result is as follows:
Unknown error division by zero

In the code above, we know that 1/0 will certainly report an error because it will execute the last error. But Will else statements be executed? We can see that the execution is not performed from the running result, so let's look at the correct situation:

Data = {} names = [] num = 1try: num/1 handle T (IndexError, KeyError) as e: # e is the incorrect trust information, cause of error print ("List Index error", e) failed t FileNotFoundError as e: print ("file does not exist", e) failed t Exception as e: print ("Unknown error ", e) else: print ("everything is OK ")
The running result is as follows:
Everything OK

From the code running result, we can see that when there is no error, the else statement is executed. We can see that when an error occurs during program execution, the else statement is not executed, when the program runs normally, it will execute the else statement, telling us that the program has no exception error. This situation is often used for testing. errors are returned and normal responses are returned.

Let's take a look at finally:

When no exception occurs:

Data = {} names = [] num = 1try: num/1 handle T (IndexError, KeyError) as e: # e is the incorrect trust information, cause of error print ("List Index error", e) failed t FileNotFoundError as e: print ("file does not exist", e) failed t Exception as e: print ("Unknown error ", e) else: print ("everything is OK") finally: print ("whether there is any error or not, run it !!! ")
The running result is as follows:
Everything OK
Run the command whether there are any errors !!!

The above shows that the finally statement is executed when the code is normal.

Let's take a look at the situation when the code is normal:

 

Data = {} names = [] num = 1try: num/0 handle T (IndexError, KeyError) as e: # e is the incorrect trust information, cause of error print ("List Index error", e) failed t FileNotFoundError as e: print ("file does not exist", e) failed t Exception as e: print ("Unknown error ", e) else: print ("everything is OK") finally: print ("whether there is any error or not, run it !!! ")
The running result is as follows:
Unknown error division by zero
Run the command whether there are any errors !!!

 

The preceding running results show that when an error occurs, the else statement is not executed, but the finally statement continues to be executed. It indicates that the finally statement is executed normally under any circumstances.

There are many types of exceptions in python. Each exception is specially used to handle an exception !!!

AttributeError attempts to access a tree without an object, such as foo. x, but foo has no attribute x

The IOError input/output is abnormal. Basically, the file cannot be opened.

ImportError cannot introduce modules or packages. It is basically a path problem or a name error.

IndentationError syntax error (subclass of); the Code is not correctly aligned

The IndexError subscript index exceeds the sequence boundary. For example, if x has only three elements, it tries to access x [5].

KeyError attempts to access a key that does not exist in the dictionary

KeyboardInterrupt Ctrl + C is pressed

NameError uses a variable that has not been assigned an object

SyntaxError Python code is invalid and the Code cannot be compiled (I think this is a syntax error and it is wrong)

TypeError: the type of the input object does not meet the requirements.

UnboundLocalError tries to access a local variable that has not been set, basically because there is another global variable with the same name, you think you are accessing it

ValueError refers to a value that the caller does not expect, even if the value type is correct

Custom exception:

When we connect to the database, if a connection error occurs, an exception will occur. The exception inherent in Python cannot be captured, so we can only capture it by ourselves. In this case, a custom exception is required. As follows:

Class MysqlConnectError (Exception): def _ init _ (self, msg): self. message = msg def _ str _ (self): return self. messagetry: raise MysqlConnectError ('My exception') handle T MysqlConnectError as e: print (e)
The running result is as follows:
My exceptions

 

The above is the exception handling situation defined by myself.

Summary:

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.