PYTHON 100days study notes 008-4: errors and exceptions

Reference article:

python3 errors and exceptions

Day008_04: python errors and exceptions

Feeling a little confused, and continue to adhere to read on, and then to look back Zayang

As a Python beginner, just learning the Python programming, we often see some error message, we did not mention earlier, this chapter will be devoted to us.

Python has two easily recognizable error: syntax errors and exceptions.

1, a syntax error

Python syntax errors or wrong call analytic, beginners often encountered, the following examples:

while True print('Hello, world')
  File "<ipython-input-1-6a04ccfba5da>", line 1
    while True print('Hello, world')
                   ^
SyntaxError: invalid syntax

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

Parser pointed out the error of his party, and mark a small arrow in the wrong place found first.

2, abnormal

Even if the syntax is correct Python program, when run it, there may be an error. Run-time error detection to be called abnormal.

Most exceptions are not handled by the program, we have demonstrated here in the form of error messages:

10 * (1/0)
---------------------------------------------------------------------------

ZeroDivisionError                         Traceback (most recent call last)

<ipython-input-2-9ce172bd90a7> in <module>()
----> 1 10 * (1/0)


ZeroDivisionError: division by zero
4 + spam*3
---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

<ipython-input-3-6b1dfe582d2e> in <module>()
----> 1 4 + spam*3


NameError: name 'spam' is not defined
'2' + 2
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-4-4c6dd5170204> in <module>()
----> 1 '2' + 2


TypeError: Can't convert 'int' object to str implicitly

Different types of abnormality occurs, these types of information are printed as part: Examples of types ZeroDivisionError, NameError and TypeError.

The front part of the error message shows the context of the exception, and displays specific information in the form of a call stack.

3, exception handling

The following example, allows users to enter a valid integer, but allows the user to interrupt the program (using Control-C or the method provided by the operating system). User information will lead to a disruption KeyboardInterrupt exception.

while True:
    try:
        x = int(input("Please enter a number: "))
        break
    except ValueError:
        print("Oops! That was no valid number. Try again   ")
Please enter a number: 12.5
Oops! That was no valid number. Try again   
Please enter a number: 12

try statement works as follows;

  • First, the try clause (the statement between the keywords and keyword except a try)
  • If no exception occurs, ignored except clause, try clause after the end of execution.
  • If an exception occurs during execution of the try clause, the rest of the try clause is ignored. If the name and type except after abnormal match, then the corresponding except clause is executed. Finally execute code after the try statement.
  • If an exception is not with any except a match, the exception will be passed to the top of the try.

A try statement may contain more than one except clause, to deal with different specific exceptions. At most one branch will be executed.

Handler only for the try clause corresponding exception processing, rather than the exception handler in the other try.

Except clause can handle multiple exceptions that will be placed in a parenthesis as a tuple, for example:


except (RuntimeError, TypeError, NameError):
        pass
      

The last except clause may ignore the name of the exception, it will be treated as a wildcard. You can use this method to print an error message, and then again the exception is thrown.

import sys

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except OSError as err:
    print("OS error: {0}".format(err))
except ValueError:
    print("Could not convert data to an interger.")
except:
    print("Unexpected error:", sys.exc_info()[0])
    raise
OS error: [Errno 2] No such file or directory: 'myfile.txt'

try except statement has an optional else clause, if you use this clause, must be placed after all except clauses. This clause will execute without any exception occurs in the try clause of time. E.g:

for arg in sys.argv[1:]:
    try:
        f = open(arg, 'r')
    except IOError:
        print('cannot open', arg)
    else:
        print(arg, 'has', len(f.readlines()), 'lines')
        f.close()
cannot open -f
C:\Users\ALL\AppData\Roaming\jupyter\runtime\kernel-1c6f120c-5ea6-4cc3-bf97-f8c1c4fb93b3.json has 12 lines

The else clause than all the statements are placed inside the try clause is better to avoid some unexpected, but except they do not capture the exception.

Exception handling does not just deal with those exceptions occur directly in the try clause, but also processing function (even indirect function call) clause invoked's thrown. E.g:

def this_fails():
    x = 1/0

try:
    this_fails()
except ZeroDivisionError as err:
    print('Handing run-time error', err)
Handing run-time error division by zero

4, throw an exception

Use Python raise statement throws a specified exception. E.g:

raise NameError('HiThreee')
---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

<ipython-input-2-9f2acf03434f> in <module>()
----> 1 raise NameError('HiThreee')


NameError: HiThreee

The only parameter specifies the raise to be thrown. It must be an unusual class instance or abnormal (i.e. Exception subclass).

If you just want to know if it throws an exception, does not want to deal with it, then a simple statement can raise it again thrown.

try:
    raise NameError('HiThere')
except NameError:
    print('An exception flew by!')
    raise
An exception flew by!



---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

<ipython-input-3-3f47609917d7> in <module>()
      1 try:
----> 2     raise NameError('HiThere')
      3 except NameError:
      4     print('An exception flew by!')
      5     raise


NameError: HiThere

5, user-defined exception

You can have your own exceptions by creating a new exception class. Exception class inherits from Exception class can inherit directly, or indirectly inheritance, for example:

class MyError(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)
    
try:
    raise MyError(2*2)
except MyError as e:
    print('My exception occurred,value:',e.value)
    
raise MyError('oops!')
My exception occurred,value: 4



---------------------------------------------------------------------------

MyError                                   Traceback (most recent call last)

<ipython-input-7-130cdfe43328> in <module>()
     10     print('My exception occurred,value:',e.value)
     11 
---> 12 raise MyError('oops!')


MyError: 'oops!'

In this example, the default class Exception the init () is covered.

When you create a module may throw a number of different abnormalities A common practice is to create a base exception class for this package, and then create different sub-classes for different error conditions on the base class:

class Error(Exception):
    """Base class for exceptions in this module."""
    pass
 
class InputError(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 = message
 
class TransitionError(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 -- explanation of why the specific transition is not allowed
    """
 
    def __init__(self, previous, next, message):
        self.previous = previous
        self.next = next
        self.message = message

Most of the unusual names that end in "Error", just like the standard exceptions named as

6, the definition of clean-up behavior

The try statement has another optional clause, which defines the clean-up will be carried out regardless of the behavior under any circumstances. E.g:

try:
    raise keyboardInterrupt
finally:
    print('GOOdbye, world!')
GOOdbye, world!



---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

<ipython-input-3-52ee0e09650c> in <module>()
      1 try:
----> 2     raise keyboardInterrupt
      3 finally:
      4     print('GOOdbye, world!')


NameError: name 'keyboardInterrupt' is not defined

Regardless of the above examples try clause, there is no exception occurs, finally clause will be executed.

If an exception in the try clause (or except and else clause) is thrown out, but do not have any except it stopped, then this exception will be thrown in after the finally clause is executed.

Here is a more complex example (contained in the same statement in a try except and finally clauses):

def divide(x, y):
    try:
        result = x / y
    except ZeroDivisionError:
        print("division by zero!")
    else:
        print("result is", result)
    finally:
        print("executing finally clause")

def main():
    divide(2, 1)
    divide(2, 0)
    divide("2", "1")

if __name__ ==  '__main__':
    divide(2, 1)
    divide(2, 0)
    divide("2", "1")
    
result is 2.0
executing finally clause
division by zero!
executing finally clause
executing finally clause



---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-10-8d2c553de996> in <module>()
     17     divide(2, 1)
     18     divide(2, 0)
---> 19     divide("2", "1")
     20 


<ipython-input-10-8d2c553de996> in divide(x, y)
      1 def divide(x, y):
      2     try:
----> 3         result = x / y
      4     except ZeroDivisionError:
      5         print("division by zero!")


TypeError: unsupported operand type(s) for /: 'str' and 'str'

7, predefined clean-up behavior

Some objects define standard clean-up behavior, regardless of whether the system is successfully used it once does not need it anymore, then the standard clean-up behavior will be executed.

This example shows this side try to open a file, then print the contents to the screen:

for line in open("myfile.txt"):
    print(line, end="")

The above problem with this code is that when finished, the file remains open, and not closed.

Keywords with statement can be guaranteed, such as object files and the like will carry out his right cleaning method after use:

with open("myfile.txt") as f:
    for line in f:
        print(line, end="")

After completion of the above code execution, even during processing problems, and file f is always closed.


END
2019-5-31 11:39:29

Guess you like

Origin www.cnblogs.com/yj411511/p/10954431.html