forked from trekhleb/learn-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_try.py
66 lines (51 loc) · 2.07 KB
/
test_try.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
"""TRY statement
@see: https://www.w3schools.com/python/python_try_except.asp
"try" statement is used for exception handling.
When an error occurs, or exception as we call it, Python will normally stop and generate an error
message. These exceptions can be handled using the try statement.
The "try" block lets you test a block of code for errors.
The "except" block lets you handle the error.
The "else" block lets you execute the code if no errors were raised.
The "finally" block lets you execute code, regardless of the result of the try- and except blocks.
"""
def test_try():
"""TRY statement"""
# The try block will generate an error, because x is not defined:
exception_has_been_caught = False
try:
# pylint: disable=undefined-variable
print(not_existing_variable)
except NameError:
exception_has_been_caught = True
assert exception_has_been_caught
# You can define as many exception blocks as you want, e.g. if you want to execute a special
# block of code for a special kind of error:
exception_message = ''
try:
# pylint: disable=undefined-variable
print(not_existing_variable)
except NameError:
exception_message = 'Variable is not defined'
assert exception_message == 'Variable is not defined'
# You can use the else keyword to define a block of code to be executed
# if no errors were raised.
message = ''
# pylint: disable=broad-except
try:
message += 'Success.'
except NameError:
message += 'Something went wrong.'
else:
message += 'Nothing went wrong.'
assert message == 'Success.Nothing went wrong.'
# The finally block, if specified, will be executed regardless if the try block raises an
# error or not.
message = ''
try:
# pylint: undefined-variable
print(not_existing_variable) # noqa: F821
except NameError:
message += 'Something went wrong.'
finally:
message += 'The "try except" is finished.'
assert message == 'Something went wrong.The "try except" is finished.'