-
Notifications
You must be signed in to change notification settings - Fork 0
/
try_except_doc
200 lines (156 loc) · 7.15 KB
/
try_except_doc
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
1. How To Handle An Arbitrary Exception
Sometimes, you may need a way to allow any arbitrary exception and also want to be able to display the error or exception message.
It is easily achievable using the Python exceptions. Check the below code. While testing, you can place the code inside the try block in the below example.
try:
#your code
except Exception as ex:
print(ex)
Back to top
2. Catch Multiple Exceptions In One Except Block
You can catch multiple exceptions in a single except block. See the below example.
except (Exception1, Exception2) as e:
pass
Please note that you can separate the exceptions from the variable with a comma which is applicable in Python 2.6/2.7. But you can’t do it in Python 3. So, you should prefer to use the [as] keyword.
Back to top
3. Handling Multiple Exceptions With One Except Block
There are many ways to handle multiple exceptions. The first of them requires placing all the exceptions which are likely to occur in the form of a tuple. Please see from below.
try:
file = open('input-file', 'open mode')
except (IOError, EOFError) as e:
print("Testing multiple exceptions. {}".format(e.args[-1]))
The next method is to handle each exception in a dedicated except block. You can add as many except blocks as needed. See the below example.
try:
file = open('input-file', 'open mode')
except EOFError as ex:
print("Caught the EOF error.")
raise ex
except IOError as e:
print("Caught the I/O error.")
raise ex
The last but not the least is to use the except without mentioning any exception attribute.
try:
file = open('input-file', 'open mode')
except:
# In case of any unhandled error, throw it away
raise
This method can be useful if you don’t have any clue about the exception possibly thrown by your program.
Back to top
4. Re-Raising Exceptions In Python
Exceptions once raised keep moving up to the calling methods until handled. Though you can add an except clause which could just have a [raise] call without any argument. It’ll result in reraising the exception.
See the below example code.
try:
# Intentionally raise an exception.
raise Exception('I learn Python!')
except:
print("Entered in except.")
# Re-raise the exception.
raise
Output:
Entered in except.
Traceback (most recent call last):
File "python", line 3, in <module>
Exception: I learn Python!
Back to top
5. When To Use The Else Clause
Use an else clause right after the try-except block. The else clause will get hit only if no exception is thrown. The else statement should always precede the except blocks.
In else blocks, you can add code which you wish to run when no errors occurred.
See the below example. In this sample, you can see a while loop running infinitely. The code is asking for user input and then parsing it using the built-in [int()] function. If the user enters a zero value, then the except block will get hit. Otherwise, the code will flow through the else block.
while True:
# Enter integer value from the console.
x = int(input())
# Divide 1 by x to test error cases
try:
result = 1 / x
except:
print("Error case")
exit(0)
else:
print("Pass case")
exit(1)
Back to top
6. Make Use Of [Finally Clause]
If you have a code which you want to run in all situations, then write it inside the [finally block]. Python will always run the instructions coded in the [finally block]. It is the most common way of doing clean up tasks. You can also make sure the clean up gets through.
An error is caught by the try clause. After the code in the except block gets executed, the instructions in the [finally clause] would run.
Please note that a [finally block] will ALWAYS run, even if you’ve returned ahead of it.
See the below example.
try:
# Intentionally raise an error.
x = 1 / 0
except:
# Except clause:
print("Error occurred")
finally:
# Finally clause:
print("The [finally clause] is hit")
Output:
Error occurred
The [finally clause] is hit
Back to top
7. Use The As Keyword To Catch Specific Exception Types
With the help of as <identifier>, you can create a new object. And you can also the exception object. Here, the below example, we are creating the IOError object and then using it within the clause.
try:
# Intentionally raise an error.
f = open("no-file")
except IOError as err:
# Creating IOError instance for book keeping.
print("Error:", err)
print("Code:", err.errno)
Output:
('Error:', IOError(2, 'No such file or directory'))
('Code:', 2)
Back to top
8. Best Practice For Manually Raising Exceptions
Avoid raising generic exceptions because if you do so, then all other more specific exceptions have to be caught also. Hence, the best practice is to raise the most specific exception close to your problem.
Bad Example.
def bad_exception():
try:
raise ValueError('Intentional - do not want this to get caught')
raise Exception('Exception to be handled')
except Exception as error:
print('Inside the except block: ' + repr(error))
bad_exception()
Output:
Inside the except block: ValueError('Intentional - do not want this to get caught',)
Best Practice:
Here, we are raising a specific type of exception, not a generic one. And we are also using the args option to print the incorrect arguments if there is any. Let’s see the below example.
try:
raise ValueError('Testing exceptions: The input is in incorrect order', 'one', 'two', 'four')
except ValueError as err:
print(err.args)
Output:
('Testing exceptions: The input is in incorrect order', 'one', 'two', 'four')
Back to top
9. How To Skip Through Errors And Continue Execution
Ideally, you shouldn’t be doing this. But if you still want to do, then follow the below code to check out the right approach.
try:
assert False
except AssertionError:
pass
print('Welcome to Prometheus!!!')
Output:
Welcome to Prometheus!!!
Back to top
Now, have a look at some of the most common Python exceptions and their examples.
Most Common Exception Errors
IOError – It occurs on errors like a file fails to open.
ImportError – If a python module can’t be loaded or located.
ValueError – It occurs if a function gets an argument of right type but an inappropriate value.
KeyboardInterrupt – It gets hit when the user enters the interrupt key (i.e. Control-C or Del key)
EOFError – It gets raised if the input functions (input()/raw_input()) hit an end-of-file condition (EOF) but without reading any data.
Back to top
Examples Of Most Common Exceptions
except IOError:
print('Error occurred while opening the file.')
except ValueError:
print('Non-numeric input detected.')
except ImportError:
print('Unable to locate the module.')
except EOFError:
print('Identified EOF error.')
except KeyboardInterrupt:
print('Wrong keyboard input.')
except:
print('An error occurred.')
Back to top
Summary – How To Best Use Try-Except In Python
while programming, errors are bound to happen. It’s a fact which no one can ignore. And there could be many reasons for errors like bad user input, insufficient file permission, the unavailability of a network resource, insufficient memory or most likely the programmer’s mistake.