Python -> (6) Learning Notes

Exception Handling

  • NameError
  • TypeError
  • Exception handling (try ... except)
  • An exception is thrown (raise)
  • finally clause

Any errors that occur during program execution is abnormal . Each exception shows related error messages, such as the use Python2 unique in Python3 syntax occurs SyntaxError, the first multi-line accidentally hit a space will generate IndentationError.

  1. NameError
    when an undefined variable access NameError will occur.
    eg,
>>> print(kushal)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'kushal' is not defined

The last line contains the details of the error, the remaining lines display the details of how it happened (or what caused the exception) are.

  1. TypeError
    when improper operation or function applied to the object type initiator, a common example is an integer addition and string are:
>>> print(1 + "kushal")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
  1. Exception Handling

Use try...exceptblocks to process any exception. The basic syntax like this:

try:
    statements to be inside try clause
    statement2
    statement3
    ...
except ExceptionName:
    statements to evaluated in case of ExceptionName happens

It works as follows:

  1. First, the tryclause (in tryand the exceptpart between the keywords).

  2. If no exception occurs, the exceptclause tryafter the statement is finished ignored.

  3. If tryan exception occurred during the execution clause, then the rest of the clauses will be ignored.
    If the exception matches the exceptexception type keyword is specified, it performs a corresponding exceptclause. Then proceed to trythe code after the statement.

  4. If an exception occurs, the exceptno branch matching clause, it is passed on to a trystatement.
    If you still can not find the corresponding final statement processing, it is an unhandled exception and execution stops with a message appears.

chestnut:

>>> def get_number():
...     "Returns a float number"
...     number = float(input("Enter a float number: "))
...     return number
...
>>>
>>> while True:
...     try:
...         print(get_number())
...     except ValueError:
...         print("You entered a wrong value.")
...
Enter a float number: 45.0
45.0
Enter a float number: 24,0
You entered a wrong value.
Enter a float number: Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
  File "<stdin>", line 3, in get_number
KeyboardInterrupt

First, I entered a suitable floating-point value, the interpreter returns the output value.

Then when I type a comma-separated values, throw ValueErrorexception exceptclause catches of, and print out an error message.

I pressed the third time Ctrl + C, led to the KeyboardInterruptexception, the exception is not caught in except block, so the program execution is suspended.

An empty exceptstatement can capture any exceptions

>>> try:
...     input() # 输入的时候按下 Ctrl + C 产生 KeyboardInterrupt
... except:
...     print("Unknown Exception")
...
Unknown Exception
  1. Throw an exception
    using the raise statement throws an exception.
>>> raise ValueError("A value error happened.")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: A value error happened.

You can capture anomalies like any other ordinary to catch them.

>>> try:
...     raise ValueError("A value error happened.")
... except ValueError:
...     print("ValueError in our code.")
...
ValueError in our code.
  1. The definition of clean-up behavior
    try statement has another optional finallyclause is intended to define in any case must be executed. E.g:
>>> try:
...     raise KeyboardInterrupt
... finally:
...     print('Goodbye, world!')
...
Goodbye, world!
KeyboardInterrupt
Traceback (most recent call last):
  File "<stdin>", line 2, in ?

Whether or not an exception occurs, the finallyclause in the program leave tryare sure to be executed later. When the trystatement is not happening exceptexception trapping (or it happens except or else clause), in finallyclause after the implementation of it will be re-thrown.

In a real application scenarios, the finallyclause is useful for releasing external resources (files or network connections and the like), regardless of whether they are of course wrong.

As mentioned in the withstatement, which is try-finallyshorthand for the block, using the withstatement to ensure the file is always closed.

What anomaly? In fact, an anomaly .

Source:
laboratory building

Published 33 original articles · won praise 1 · views 1251

Guess you like

Origin blog.csdn.net/weixin_44783002/article/details/104582010