Python standard exception Development experience summary

Source: Internet
Author: User
Tags finally block throw exception
There are always a lot of anomalies and errors when we write scripts or software development, and Python has two very important functions that can handle exceptions and any unexpected errors, and these two functions are exception handling and assertion.

Exception handling: Mainly includes syntax errors and other standard exceptions, the standard exceptions are described in the following table.

Assertion: An assertion is a sanity check that you can turn on or off when the program's test is complete. The simplest way to assert is to compare it to a raise-if statement (or, more precisely, to add a raise-if-not declaration). An expression is tested, and if the result appears false, an exception is thrown. Assertions are keywords that are used in the Python1.5 version by ASSERT statements, new keywords in python.

Programmers often place assertions to check for input validity, or check for valid output after a function call.

First, the standard exception table

Exception Example:

 1, filenotfounderror try to open d:\\openstack.txt file because the file does not exist, it will be reported filenotfounderror:f =open ("D:\\openstack.txt") Traceback (most recent call last): File ' <pyshell#0> ', line 1, in <module> f=ope N ("D:\\openstack.txt") Filenotfounderror: [Errno 2] No such file or directory: ' D:\\openstack.txt ' 2,  Zerodivisionerror division operation or modulo operation with a divisor of zero >>> 5/0traceback (most recent call last): File "<pyshell#1>", line 1, In <module> 5/0zerodivisionerror:division by Zero3, Importerror is generally in the import module, because the module does not exist and other reasons cause error >>> import wwww Traceback (most recent): File "<pyshell#2>", line 1, <module> import wwwwimporterror:no mod Ule named ' wwww ' 4, ValueError is generally due to the data type of the incoming parameters error caused by errors. >>> a= "STERC" >>> Int (a) Traceback (most recent call last): File ' <pyshell#4> ', line 1, in <modu le> Int (a) valueerror:invalid literal for int. () with base: ' Sterc ' >>> 

Second, exception handling

Python contains two exception-handling statements that can be used try...except...finally or try...except. Else statement to handle the exception, the syntax for both statements and the difference between the two are briefly described:

Try statement principle:

First, execute the TRY clause (the statement between the keyword try and the keyword except)

If no exception occurs, the EXCEPT clause is ignored, and the try clause finishes after execution.

If an exception occurs during the execution of a try clause, the remainder of the try clause is ignored. If the type of the exception matches the name after except, then the corresponding except clause is executed. The code after the last try statement is executed.

If an exception does not match any of the except, then the exception is passed to the upper try.

A try statement may contain multiple except clauses that handle different specific exceptions. Only one branch will be executed at most.

The handler will handle only the exceptions in the corresponding try clause, not the exceptions in the other try handlers.

A except clause can handle multiple exceptions at the same time, and these exceptions will be placed in parentheses as a tuple.

Try...except. else syntax:

Try: You did   your operations here   ... except Exceptioni:   If There is Exceptioni, and then-------- Execute this block.except exceptionii:   If There is exceptionii and then execute this block.   ... else:   If There is no exception then execute the this block.     ".". ".". A single Try statement can have more than one except statement. You can include an else clause when a try block contains an exception declaration that may throw different types, which is useful, or you can provide a generic except clause to handle exceptions (not advocated) except clauses. If the code is in try: The block does not throw an exception then the code executes in the else block else is the code that can run the normal part of the exception, which does not require a try: The block's protection  try:   fh = open ("Testfile", "w+")   Fh.write ( "This was my test file for exception handling!!") Except IOError:   print ("error:can\ ' t find file or read data") Else:   print ("written content in the file SUCCESSF Ully ")   Fh.close () The     contents of the Testfile file will be generated after the normal execution: This is my test file for exception handling!  The console output results are as follows:  written content in the file successfully

Handling multiple exceptions with the EXCEPT clause

Just now our example is dealing with one type of exception, while except can handle multiple types of exceptions, such as

Except (Valueerror,importerror,runtimeerror) it is possible to write multiple types of standard errors into a tuple, but it is difficult to make a type of error analysis for our team type easily.

Try:   fh = open ("Testfile", "R")   Fh.write ("This was my test file for exception handling!!") Except (valueerror,importerror,runtimeerror):   print ("error:can\ ' t find file or read data") Else:   print (" Written content in the file successfully ")   Fh.close ()  result:  error:can ' t find file or read data  #这里没有报出是那个类 Standard error of type.

try-finally clause:

Use try: block. The finally block is mandatory, regardless of whether the try block throws an exception or not. The syntax for the try-finally statement is this.

Try:   your operations here;   ......................   Due to any exception, this is may skipped.
Except Exceptioni:   If there is Exceptioni and then execute this block.except exceptionii:   If there is exceptionii, th En execute this block.

Finally

   This would always be executed.

Try...except...finally regardless of whether the try block can be executed normally, finally is a module that is bound to execute.

Try:   fh = open ("Testfile", "R")   Fh.write ("This was my test file for exception handling!!") Except (valueerror,importerror,runtimeerror):   print ("error:can\ ' t find file or read data") Finally:   print (" Written content in the file successfully ")   Fh.close () #关闭文件  Result: Nothing is written in the file, the  console outputs the following: Error:can ' t find file or read Datawritten content in the file successfully

Throw exception

You can trigger several aspects of an exception by using the Raise statement. The general syntax for the raise statement is as follows.

Grammar

raise [Exception [, Args [, Traceback]]

Here, Exception is the parameter value of the exception type (for example, nameerror) argument is an exception. The parameter is optional, and if not provided, the exception parameter is none.

The last parameter, Traceback, is also optional (rarely used in practice) and, if present, is a backtracking object for the exception.

Example

An exception can be a string, a class, or an object. Most python's exception core is the exception that triggers the class exception, using an instance parameter of the class. It is easy to define a new exception, which can be done as follows-

def functionname (level):    if level <1:        raise Exception (Level)        # The code below to this would not being execut Ed        # If we raise the exception    return level

Note: In order to catch an exception, a "except" statement must be an exception that indicates a thrown class object or a simple string exception. For example, to catch an exception above, we must write the EXCEPT clause as follows--

Try: Business   Logic here...except Exception as E:   Exception handling here using E.args...else:   Rest of the Cod e here ...

The following example shows how to use the trigger exception:

#!/usr/bin/python3def functionname:    if level <1:        raise Exception (Level)        # The code below to this W Ould not being executed        # if we raise the exception    return level try:    l=functionname ( -10)    print ("level=", L) Except Exception as E:    print ("Error in level argument", E.args[0])

This will produce the following results

Error in Level argument-10

User-defined exceptions

In Python, you can also create your own exceptions by using the built-in exception standard derived class.

Here is an example of a runtimeerror. Here a class is created, which is a subclass of RuntimeError. When needed, an exception can be captured to display more specific information, which is useful.

In the try block, the user-defined exception is thrown and clipped in the except block. The variable e is an instance of the Networkerror class that is used to create a network error.

Class Networkerror (RuntimeError):   def __init__ (self, arg):      Self.args = arg

So after the above class definition, you can throw an exception as follows-

Try:   raise Networkerror ("bad hostname") except Networkerror,e:   print E.args
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.