summaryrefslogtreecommitdiff
path: root/basic_python/exceptions.tex
blob: 766dc9869cf836778a55c6ca1ef9d1c17e4f6507 (plain)
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Tutorial slides on Python.
%
% Author: FOSSEE
% Copyright (c) 2017, FOSSEE, IIT Bombay
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\documentclass[14pt,compress]{beamer}
\input{macros.tex}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Title page
\title[Exceptions]{Python language: exceptions}

\author[FOSSEE Team] {The FOSSEE Group}

\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay}
\date[] {Mumbai, India}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% DOCUMENT STARTS
\begin{document}

\begin{frame}
  \titlepage
\end{frame}

\begin{frame}{Motivation}
    \begin{itemize}
        \item How do you signal errors to a user?
    \end{itemize}
\end{frame}

\begin{frame}
  \frametitle{Exceptions}
  \begin{itemize}
  \item Python's way of notifying you of errors
  \item Several standard exceptions: \texttt{SyntaxError}, \texttt{IOError}
    etc.
  \item Users can also \texttt{raise} errors
  \item Users can create their own exceptions
  \item Exceptions can be ``caught'' via \texttt{try/except} blocks
  \end{itemize}
\end{frame}

\begin{frame}[fragile]
 \frametitle{Exceptions: examples}
 \begin{lstlisting}
In []: while True print('Hello world')
 \end{lstlisting}
\pause
  \begin{lstlisting}
File "<stdin>", line 1, in ?
    while True print('Hello world')
                   ^
SyntaxError: invalid syntax
\end{lstlisting}
\end{frame}

\begin{frame}[fragile]
 \frametitle{Exceptions: examples}
 \begin{lstlisting}
In []: print(spam)
\end{lstlisting}
\pause
\begin{lstlisting}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'spam' is not defined
\end{lstlisting}
\end{frame}

\begin{frame}[fragile]
 \frametitle{Exceptions: examples}
 \begin{lstlisting}
In []: 1 / 0
\end{lstlisting}
\pause
\begin{lstlisting}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division
or modulo by zero
\end{lstlisting}
\end{frame}


\begin{frame}[fragile]
  \frametitle{Exceptions: examples}
\begin{lstlisting}
In []: '2' + 2
\end{lstlisting}
\pause
\begin{lstlisting}
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: cannot concatenate 'str' and 'int' objects
\end{lstlisting}
\end{frame}


\begin{frame}[fragile]
  \frametitle{Processing user input}
  \begin{lstlisting}
prompt = 'Enter a number(Q to quit): '
a = input(prompt)

num = int(a) if a != 'Q' else 0
  \end{lstlisting}
  \emphbar{What if the user enters some other alphabet?}
\end{frame}


\begin{frame}[fragile]
  \frametitle{Handling Exceptions}
  Python provides a \typ{try} and \typ{except} clause.
  \begin{lstlisting}
prompt = 'Enter a number(Q to quit): '
a = input(prompt)
try:
    num = int(a)
    print(num)
except:
    if a == 'Q':
        print("Exiting ...")
    else:
        print("Wrong input ...")
  \end{lstlisting}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Handling Exceptions a little better}
  Use specific exceptions; avoid blanket except clauses
  \begin{lstlisting}
prompt = 'Enter a number(Q to quit): '
a = input(prompt)
try:
    num = int(a)
    print(num)
except ValueError:
    if a == 'Q':
        print("Exiting ...")
    else:
        print("Wrong input ...")
  \end{lstlisting}
\end{frame}


\begin{frame}[fragile]
  \frametitle{Exceptions: examples}
  \small
\begin{lstlisting}
prompt = "Enter a number: "
while True:
    try:
        x = int(input(prompt))
        break
    except ValueError:
        print("Invalid input, try again...")

\end{lstlisting}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Catching multiple exceptions}
\begin{lstlisting}
data = input()
try:
    x = int(data.split(',')[1])
    break
except IndexError:
    print('Input at least 2 values.')
except ValueError:
    print("Invalid input, try again...")

\end{lstlisting}
\end{frame}


\begin{frame}[fragile]
  \frametitle{Catching multiple exceptions}
\begin{lstlisting}
data = input()
try:
    x = int(data.split(',')[1])
    break
except (ValueError, IndexError):
    print("Invalid input ...")

\end{lstlisting}
\end{frame}

\begin{frame}[fragile]
  \frametitle{\typ{try, except, else}}
\begin{lstlisting}
data = input()
try:
    x = int(data.split(',')[1])
    break
except (ValueError, IndexError):
    print("Invalid input ...")
else:
    print('All is well!')
  \end{lstlisting}

\end{frame}


\begin{frame}
  \frametitle{Some comments}
  \begin{itemize}
  \item In practice NEVER use blanket except clauses
  \item Always catch specific exceptions
  \end{itemize}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Exceptions: raising your exceptions}
\small
\begin{lstlisting}
>>> raise ValueError("your error message")
Traceback (most recent call last):
  File "<stdin>", line 2, in ?
ValueError: your error message
\end{lstlisting}
\end{frame}



\begin{frame}[fragile]
  \frametitle{Exceptions: try/finally}
  \small
\begin{lstlisting}
while True:
    try:
        x = int(input(prompt))
        break
    except ValueError:
        print("Invalid number, try again...")
    finally:
        print "All good!"

      \end{lstlisting}
      \normalsize
      Always runs the finally clause!
\end{frame}


\begin{frame}[fragile]
  \frametitle{Exceptions: try/finally}
  \begin{lstlisting}
def f(x):
    try:
        y = int(x)
        return y
    except ValueError:
        print(x)
    finally:
        print('finally')

>>> f(1)
>>> f('a')
\end{lstlisting}
Always runs the finally clause!
\end{frame}


\begin{frame}
  \frametitle{Summary}
  \begin{itemize}
  \item Catching exceptions with \typ{try/except}
  \item Catching multiple exceptions
  \item Cleanup with \typ{finally}
  \item Raising your own exceptions
  \end{itemize}
\end{frame}

\begin{frame}
  \frametitle{What next?}
  \begin{itemize}
  \item Only covered the very basics
  \item More advanced topics remain
  \item Read the official Python tutorial:
    \url{docs.python.org/tutorial/}
  \end{itemize}
\end{frame}

\end{document}