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
.
- 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.
- 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'
- Exception Handling
Use try...except
blocks 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:
-
First, the
try
clause (intry
and theexcept
part between the keywords). -
If no exception occurs, the
except
clausetry
after the statement is finished ignored. -
If
try
an exception occurred during the execution clause, then the rest of the clauses will be ignored.
If the exception matches theexcept
exception type keyword is specified, it performs a correspondingexcept
clause. Then proceed totry
the code after the statement. -
If an exception occurs, the
except
no branch matching clause, it is passed on to atry
statement.
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 ValueError
exception except
clause catches of, and print out an error message.
I pressed the third time Ctrl + C
, led to the KeyboardInterrupt
exception, the exception is not caught in except block, so the program execution is suspended.
An empty except
statement can capture any exceptions
>>> try:
... input() # 输入的时候按下 Ctrl + C 产生 KeyboardInterrupt
... except:
... print("Unknown Exception")
...
Unknown Exception
- 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.
- The definition of clean-up behavior
try
statement has another optionalfinally
clause 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 finally
clause in the program leave try
are sure to be executed later. When the try
statement is not happening except
exception trapping (or it happens except or else clause), in finally
clause after the implementation of it will be re-thrown.
In a real application scenarios, the finally
clause 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 with
statement, which is try-finally
shorthand for the block, using the with
statement to ensure the file is always closed.
What anomaly? In fact, an anomaly 类
.
Source:
laboratory building