Python Learning note Seven-errors and exceptions

Source: Internet
Author: User

Programmers always have to deal with various errors, it is necessary to learn how to identify and correctly handle program errors.

7.1 Errors and exceptions

1. Error

In terms of software, errors are divided into grammatical and logical errors. Both of these errors will cause the program to fail normally, and when Python detects an error, an exception occurs.

2. Abnormal

When the compiler detects an error and realizes the error condition. The interpreter throws an exception (the programmer can also throw an exception himself, which is said later).

The following are some of the common errors in 7 python.

1, Nameerror, try to access an unspecified example.

2, zerodivisionerror, 0 except error.

3, Synataxerror, interpreter syntax error.

4. Indexerror, the requested index is out of range.

5, Keyerror, request a non-existent dictionary key.

6, IOError, input and output errors, such as trying to open a nonexistent file.

7. Attributeerror, try to access the object properties as unknown.

7.2 Anomaly detection and exception handling

7.2.1 TRY-EXCEP Statements

Try :    Filetest=open ('blash','r')except  ioerror,e:    print'could not open file'

At this point the program does not stop when an input and output error occurs, but instead catches the exception to display a predefined string. It is important to note that the print statement is executed only when IOError is captured, and the program stops when other types of exceptions occur, and we may need a try statement with more than one except.

7.2.2 a try statement with multiple except

You can connect multiple except statements as follows

Except Exception1[,reason1]:

Suit_for_exception1

Except Exception2[,reason2]:

Sut_for_exception2

The program executes without an error ignoring all except statements and, if an exception occurs, finds a matching exception in multiple except statements. This enables you to capture multiple types of exceptions and help us handle errors.

7.2.3 Catch all exceptions

Many exceptions can be caught based on the statements above with multiple except, but in fact the program will always have unexpected exceptions, all of which would be helpful if we could catch all the exceptions and not just the exceptions we specified.

But there's a flaw in capturing all the exceptions, which is that it doesn't tell you what exceptions are caught, nor does it allow you to deal with different types of exceptions.

Its usage is:

Try :     except (keyboardinterrupt,systemexit):     # user wants quit    Raise except Exception:     # Handle Real Errors

What needs to be explained is that keyboardinterrupt,systemexit is not really the exception, the former is the user presses CTRL + C and the latter indicates that the program needs to exit, so want the program to exit normally without being caught exception requires the above code.

7.2.4 getting the cause of the exception

After catching an exception, only the reason for the exception to occur can help us improve.

Use of the except statement:

Except Exception[,reason]

The reason in parentheses is the cause of the exception, the exception parameter. Exception parameters can be ignored and reason is required if the reason for accessing the exception is required. Reason is a class instance that contains diagnostic information for the code that caused the exception, although the name of the exception tells you what kind of exception occurred, but reason will provide more exception information.

Use the following:

def Safe_float (object):     Try :        retval=Float (object)    except  (Valueerror,typeerror), Reason:        retval =Str (reason)    return  retvalprint safe_float (' XYZ ')

The program will display could not convert string to FLOAT:XYZ, and the compiler has returned the specific cause of the error.

7.2.5 Else statement

We have seen the If-else,while-else statement, and Try-except-else is of course also available, meaning that there is no exception check within the try scope to execute the ELSE statement.

7.2.6 finally statement

The finally clause in try-except-finally represents a piece of code that executes regardless of whether the exception is caught. Of course the "try-except-else-finally" is perfectly matched. It's very simple not to say more, it is important to note that the except statement can have more than one, but at least one. The else and finally are optional.

7.3 Exception triggering

7.3.1 Raise statements

Sometimes we may need to throw an exception, which requires a raise statement at this point. Use the following:

raise [Someexception[,args[,traceback]]

The first parameter, someexception, is necessary, and you need to provide the name of the exception to throw. The second parameter, args, passes the argument to the exception, and the third parameter is the trace record (Traceback) record used for exception-normalization (exception-narmally). When the program runs to the raise statement, it jumps out and throws the exception you want.

7.4 Assertions

7.4.1 assertions can be understood as (raise if not ...) Throws an exception when the Boolean value is false. The assertion keyword is assert and is used as follows:

Assert Expression[,arguments]

The expression is followed by the exception parameter that we provide.

Python Learning note Seven-errors and exceptions

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.