Basic Python Tutorial "reading notes"-2016/7/5

Source: Internet
Author: User
Tags stack trace throw exception

Hope to continue to update through the blog park, share and record the basic knowledge of Python to the advanced application of the dots drop!

Third Wave: 8th Chapter Anomaly

[Overview] Learn how to create and raise custom exceptions, and the various ways to handle exceptions.

  In order to be able to handle exception events, conditional statements can be used wherever such events may occur, but this may not only be inefficient and inflexible, but it will also make the program difficult to read. Python's exception objects provide a very powerful alternative solution.

[8.1] What is an exception

  Python uses exception objects (exception object) to represent exception conditions. An exception is thrown when an error is encountered. If the exception object is not handled or captured, the program terminates execution with the so-called backtracking (Traceback, an error message).

In fact, each exception is an instance of some class that can be thrown, and can be captured in several ways, so that the program can catch the error and handle it, rather than having the entire program fail.

[8.2] make mistakes in your own way

Exceptions can be raised automatically when something goes wrong. Learn how to throw an exception---or even create your own exception type.


[8.2.1] Raise statement

To throw an exception, you can call the raise statement using either a class (which should be a subclass of exception) or an instance parameter. No program automatically creates an instance when you use a class. Use the built-in exception exception class as follows:

Raise Exception

Raise Exception (' hyperdrive overload ')

The first example raise exception throws a generic exception with no information about the error, and in the latter case, some hyperdive overload error messages are added.

There are many built-in exception classes, and built-in exceptions can be found in the exception module. Use the Dir function to list the contents of the module:

Import exception

Dir (Exception)

  All of these exceptions can be used in the Raise statement:

Raise Arithmeticerror

Table 8-1 Some of the built-in exceptions

Class Name Description

Exception base class for all exceptions

Attributeerror attribute reference or assignment fails when a value is raised

IOError thrown when attempting to open a file that does not exist

Indexerror thrown when using an index that does not exist in the sequence

Keyerror thrown when using a key that does not exist in the map

Nameerror thrown when a name (variable) is not found

SyntaxError thrown when the code is in the wrong form

TypeError thrown when a built-in operation or function is applied to an object of the wrong type

ValueError is thrown when a built-in operation or function is applied to an object of the correct type, but the object uses an inappropriate value.

Zerodivisionerror The second argument of a division or modulo operation is 0 o'clock

[8.2.2] Custom Exception class

There are times when you create your own exception classes. So how do you create your own exception class? Just to make sure that you inherit from the exception class (either indirectly or directly, that is, inheriting other built-in exception classes is also possible), writing a custom exception class is basically the following:

Class Somecustomexception (Exception):p

[8.3] Catching exceptions

The most interesting thing about exceptions is that they can be handled (often called trapping or catching exceptions) and can be implemented using try/except.

To catch the exception and make some error handling, as follows:

Try

X=input (' Enter The first number: ')

Y=input (' Enter The second number: ')

Print x/y

Except Zerodivisionerror:

Print "The second number can ' t be zero!"

It seems easier to check the Y value with an if statement, but if you need to add more division to your program, you have to add an if statement for each division. Using try/except, however, requires only one error handler.

If you catch a CI, but want to re-throw it (that is, to pass an exception), you can call raise without parameters.

Class Muffledcalculator:

Muffled=false

Def calc (self,expr):

Try

return eval (expr)

Except Zerodivisionerror:

If self.muffled:

print ' Division by zero ' illegal '

Else

Raise

[8.4] More than one except clause

You can add another except clause after the same try/except statement.

Try

X=input (' Enter The first number: ')

Y=input (' Enter The second number: ')

Print x/y

Except Zerodivisionerror:

Print "The second number can ' t be zero!"

Except TypeError:

Print "That Wan ' t a number, is it?"

It should be noted that exception handling does not confuse the original code, and adding a lot of if statements to check for possible error conditions can make the code quite difficult.

[8.5] capturing two exceptions with one block

If you need to catch more than one type of exception with a block, you can list them as tuples, like this:

Try

X=input (' Enter The first number: ')

Y=input (' Enter The second number: ')

Print x/y

Except (Zerodivisionerror,typeerror,nameerror):

print ' Your number were bogus ... '

Note the parentheses outside the exception object in the EXCEPT clause are important. Ignoring them is a common mistake.

[8.6] Capturing objects

  If you want to access the exception object itself in the EXCEPT clause, you can use two parameters. Note that even if you catch multiple exceptions, you only need to provide a parameter to the EXCEPT clause. This is useful if you want to keep the program running, but for some reason you want to record the error.

Try

X=input (' Enter The first number: ')

Y=input (' Enter The second number: ')

Print x/y

Except (Zerodivisionerror,typeerror), E:

Print E

[8.7] true full capture

If you really want to catch all the exceptions in a piece of code, you can omit all exception classes in the EXCEPT clause:

Try

......

Except

print ' Something wrong happened ... '

It is dangerous to catch all exceptions, because it hides errors that all programmers do not expect to be prepared to handle.

[8.8] Everything is OK

  You can give the TRY/EXCEPT statement price ELSE clause as you would for a condition and a looping statement:

Try

print ' A simple task '

Except

print ' What? Something went wrong! '

Else

print ' Ah ... It went as planned! '

[8.9] finally ...

The last is the finally clause, which can be used to clean up after a possible exception, which is used in conjunction with a try clause:

X=none

Try

x=1/0

Finally

print ' Cleaning up ... '

del X

In the preceding code, the finally clause is bound to be executed, regardless of whether an exception occurs in the TRY clause. Because deleting a variable with the DEL statement is a very irresponsible cleanup, the finally clause is useful for closing a file or network socket. You can also combine use of try, except, finally, and else in the same statement.

Try

1/0

Except Nameerror:

print ' Unknown variable '

Else

Print "That went well!"

Finally

Print "Cleaning up ..."

[8.10] Exceptions and functions

  Exceptions and functions can work very naturally together. If an exception is thrown inside a function without being processed, it propagates to the place where the function is called. If the exception is not handled there, it will continue to propagate and reach the main program (global scope). If there is no exception handler, the program will abort with the stack trace.

[8.11] Unusual Zen

  Exception handling is not very complex. If you know that a piece of code may cause an exception, and you do not want the program to be terminated as a stack trace, you can add try/except or try/finally statements for processing as long as you want.

[8.12] Summary

Exception object: exception condition can be represented by an exception object.

  Warning: warnings are similar to exceptions, but generally only print error messages.

  Throw Exception: You can throw an exception using the Raise statement. It accepts an exception class or an exception instance as a parameter, and can provide two parameters (exception and error information).

  Custom Exception classes: You can create your own exception classes by inheriting the methods of the exception class.

  catch Exception: use the except clause of the TRY statement to catch the exception. Exceptions can be placed in tuples to implement multiple exception sets. If the except is given two parameters, the 2nd parameter is bound to the exception object. Similarly, you can include multiple except clauses in a try/except statement to handle different exceptions separately.

  ELSE clause: If no exception is thrown in the main try block, the ELSE clause is executed.

  finally: If you need to make sure that some code executes regardless of whether or not an exception is thrown, the code can be prevented in the finally clause.

Exceptions and functions: When an exception is thrown within a function, it is propagated to the place where the function is called.

Basic Python Tutorial "reading notes"-2016/7/5

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.