Abnormal handling of Python3

Source: Internet
Author: User
Tags stack trace stdin

1. Syntax errors and exceptions

(1) Syntax error

The syntax error of Python, or it is called parsing fault, is often encountered by beginners, the following example:

 while Print ('HelloWorld')   " <stdin> " inch <module>      while Print ('HelloWorld')                    ^Syntaxerror:invalid Syntax

In this example, the function print () is checked for errors, and a colon (:) is missing in front of it.

The parser points to the wrong line and marks a small arrow at the location of the first found error.

(2) Abnormal

Even if the syntax of the Python program is correct, an error may occur when you run it. The run-time detected error is called an exception.

Most exceptions are not handled by the program, and are displayed in the console in the form of an error message:

>>> 10 * (1/0) Traceback (most recent): File"<stdin>", Line 1,inch<module>zerodivisionerror:division by Zero>>> 4 + spam*3Traceback (most recent): File"<stdin>", Line 1,inch<module>nameerror:name'spam'  is  notdefined>>>'2'+ 2Traceback (most recent): File"<stdin>", Line 1,inch<module>typeerror:can'T Convert'Int'object to str implicitly

Exceptions occur in different types, which are printed as part of the information: the types in the examples are zerodivisionerror,nameerror and TypeError.

The previous section of the error message shows the context in which the exception occurred and displays the specific information as the call stack.

2. Exception handling

When writing a program, if we know that a piece of code might cause some kind of exception, and do not want the program to terminate in the form of a stack trace, then we can add try/except try/finally it or the statement (or a combination of them) to handle as needed. In general, the following forms of use are available:

Try... except ... Try... except... Else ... Try... except... Else... finally ... Try... except... except... Else... finally ... Try... finally...
(1) Using try/except to catch exceptions

The Try statement works in the following manner;

    • 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 the exceptions are placed in parentheses into a tuple, for example:

except (RuntimeError, TypeError, nameerror):         Pass

The last except clause can ignore the name of the exception and it will be used as a wildcard character. You can use this method to print an error message and then throw the exception again.

ImportSYSTry: F= Open ('Test.txt') s=f.readline () I=Int (S.strip ())exceptOSError as err:Print("OS Error: {0}". Format (err))exceptValueError:Print("Could not convert data to an integer.")except:    Print("Unexpected error:", Sys.exc_info () [0])Raise

The try except statement also has an optional else clause, which, if used, must be placed after all the except clauses. This clause will be executed when no exception occurs in the TRY clause. For example:

 forArginchSys.argv[1:]:    Try: F= Open (ARG,'R')    exceptIOError:Print('cannot open', Arg)Else:        Print(ARG,' has', Len (F.readlines ()),'Lines') F.close ()

It is better to use the ELSE clause than to put all the statements in a try clause, which avoids unexpected, except, and uncaught exceptions.

Exception handling not only handles exceptions that occur directly in a try clause, but also handles exceptions thrown in functions called in clauses (even indirectly called functions). For example:

def this_fails ():         = 1/0   try:        this_fails ()    except  zerodivisionerror as err:         Print ('handling run-time Error:', err)   Handling runor modulo by zero
(2) finaly clause

The content of the finally statement block is usually done with some sort of funeral, such as a resource release, and the finally statement block is executed anyway, even if there is a return in the previous try and except statement block, Now executes the finally statement and executes the preceding return statement. Let's look at a simple example:

deftrytest ():Try: Den= Input ("input a number:") x= 1.0/Int (DEN)Printxreturn1exceptException, E:Printereturn0finally:          Print "This is a finally test"result=trytest ()PrintResult

So anyway the code in the finally statement block is executed, and if there is a return statement in Finally, then the entire function is returned from the return statement in Finally, and the preceding return statement is useless.

3. Throwing Exceptions

Python throws a specified exception using the Raise statement. For example:

Raise Nameerror ('hithere') Traceback (most recent)  :"< stdin>"in<module>nameerror:hithere

Raise only one parameter specifies the exception to be thrown. It must be an instance of an exception or an exception class (that is, a subclass of Exception).

If you just want to know if this throws an exception and don't want to deal with it, then a simple raise statement can throw it again.

>>>Try:        RaiseNameerror ('Hithere')    exceptNameerror:Print('An exception flew by!')        RaiseAn exception flew by! Traceback (most recent): File"<stdin>", Line 2,inch <module>nameerror:hithere
4. User-defined exceptions

You can have your own exception by creating a new Exception class. Exceptions should inherit from the Exception class, either directly or indirectly, for example:

>>>classMyerror (Exception):def __init__(self, value): Self.value=valuedef __str__(self):returnrepr (Self.value)>>>Try:        RaiseMyerror (2*2)    exceptMyerror as E:Print('My exception occurred, value:', E.value) My exception occurred, value:4>>>RaiseMyerror ('oops!') Traceback (most recent): File"<stdin>", Line 1,inch ?__main__. Myerror:'oops!'

In this example, the class Exception default __init__ () is overwritten.

When creating a module that is likely to throw many different exceptions, it is common practice to create a base exception class for the package, and then, based on the underlying class, to make different subclasses for different error conditions:

classError (Exception):"""Base class for exceptions in the This module."""    PassclassInputerror (Error):"""Exception raised for errors in the input.    Attributes:expression--input expression in which the error occurred message--explanation of the error """    def __init__(self, expression, message): Self.expression=expression Self.message=messageclassTransitionerror (Error):"""raised when an operation attempts a state transition that's not allowed. Attributes:previous-State at beginning of transition next--attempted new state message--EXPLA Nation of why the specific transition are not allowed"""    def __init__(self, previous, Next, message): Self.previous=previous Self.next=Next Self.message= Message

Most of the names of the exceptions end with "Error" and are named after the standard exception.

Abnormal handling of Python3

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.