Source

JythonBook / html / chapter5.html

Full commit
Josh Juneau d9b2bb8 






























































































































































































































































































































































































































































































































































































































































































  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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>Chapter 5: Exception Handling and Debugging &mdash; Jython Book v0.1 documentation</title>
    <link rel="stylesheet" href="_static/default.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '',
        VERSION:     '0.1',
        COLLAPSE_MODINDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <link rel="top" title="Jython Book v0.1 documentation" href="index.html" />
    <link rel="next" title="Chapter 6: Object Oriented Jython" href="chapter6.html" />
    <link rel="prev" title="Chapter 3: Operators, Expressions, and Program Flow" href="chapter3.html" /> 
  </head>
  <body>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="chapter6.html" title="Chapter 6: Object Oriented Jython"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="chapter3.html" title="Chapter 3: Operators, Expressions, and Program Flow"
             accesskey="P">previous</a> |</li>
        <li><a href="index.html">Jython Book v0.1 documentation</a> &raquo;</li> 
      </ul>
    </div>  

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  <div class="section" id="chapter-5-exception-handling-and-debugging">
<h1>Chapter 5: Exception Handling and Debugging<a class="headerlink" href="#chapter-5-exception-handling-and-debugging" title="Permalink to this headline"></a></h1>
<p>Any good program makes use of a language’s exception handling mechanisms.  There is no better way to frustrate an end-user then by having them run into an issue with your software and displaying a big ugly error message on the screen, followed by a program crash.  Exception handling is all about ensuring that when your program encounters an issue, it will continue to run and provide informative feedback to the end-user or program administrator.  Any Java programmer becomes familiar with exception handling on day one, as some Java code won’t even compile unless there is some form of exception handling put into place via the try-catch-finally syntax.  Python has similar constructs to that of Java, and we’ll discuss them in this chapter.</p>
<p>After you have found an exception, or preferably before your software is distributed, you should go through the code and debug it in order to find and repair the erroneous code.  There are many different ways to debug and repair code; we will go through some debugging methodologies in this chapter.  In Python as well as Java, the <em>assert</em> keyword can help out tremendously in this area.  We’ll cover <em>assert</em> in depth here and learn the different ways that it can be used to help you out and save time debugging those hard-to-find errors.</p>
<div class="section" id="exception-handling-syntax-and-differences-with-java">
<h2>Exception Handling Syntax and Differences with Java<a class="headerlink" href="#exception-handling-syntax-and-differences-with-java" title="Permalink to this headline"></a></h2>
<p>Java developers are very familiar with the <em>try-catch-finally</em> block as this is the main mechanism that is used to perform exception handling.  Python exception handling differs a bit from Java, but the syntax is fairly similar.  However, Java differs a bit in the way that an exception is <em>thrown</em> in code.  Now, realize that I just used the term <em>throw</em> …this is Java terminology.  Python does not <em>throw</em> exceptions, but instead it <em>raises</em> them.  Two different terms which mean basically the same thing.  In this section, we’ll step through the process of handling and raising exceptions in Python code, and show you how it differs from that in Java.</p>
<p>For those who are unfamiliar, I will show you how to perform some exception handling in the Java language.  This will give you an opportunity to compare the two syntaxes and appreciate the flexibility that Python offers.:</p>
<div class="highlight-python"><pre>try {
    // perform some tasks that may throw an exception
} catch (ExceptionType messageVariable) {
    // perform some exception handling
} finally {
    // execute code that must always be invoked
}</pre>
</div>
<p>Now let’s go on to learn how to make this work in Python.  Not only will we see how to handle and raise exceptions, but you’ll also learn some other great techniques later in the chapter.</p>
<div class="section" id="catching-exceptions">
<h3>Catching Exceptions<a class="headerlink" href="#catching-exceptions" title="Permalink to this headline"></a></h3>
<p>How often have you been working in a program and performed some action that caused the program to abort and display a nasty error message?  It happens more often than it should because most exceptions can be caught and handled nicely.  By nicely, I mean that the program will not abort and the end user will receive a descriptive error message stating what the problem is, and in some cases how it can be resolved.  The exception handling mechanisms within programming languages were developed for this purpose.</p>
<p>Below is a table of all exceptions that are built into the Python language along with a description of each.  You can write any of these into a clause and try to handle them.  Later in this chapter I will show you how you and        them if you’d like.  Lastly, if there is a specific type of exception that you’d like to throw that does not fit any of these, then you can write your own exception type object.</p>
<table border="1" class="docutils">
<colgroup>
<col width="33%" />
<col width="67%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">Exception</th>
<th class="head">Descripton</th>
</tr>
</thead>
<tbody valign="top">
<tr><td>BaseException</td>
<td>This is the root exception for all others</td>
</tr>
<tr><td>GeneratorExit</td>
<td>Raised by close() method of generators for terminating iteration</td>
</tr>
<tr><td>KeyboardInterrupt</td>
<td>Raised by the interrupt key</td>
</tr>
<tr><td>SystemExit</td>
<td>Program exit</td>
</tr>
<tr><td>Exception</td>
<td>Root for all non-exiting exceptions</td>
</tr>
<tr><td>StopIteration</td>
<td>Raised to stop an iteration action</td>
</tr>
<tr><td>StandardError</td>
<td>Base class for all built-in exceptions</td>
</tr>
<tr><td>ArithmeticError</td>
<td>Base for all arithmetic exceptions</td>
</tr>
<tr><td>FloatingPointError</td>
<td>Raised when a floating-point operation fails</td>
</tr>
<tr><td>OverflowError</td>
<td>Arithmetic operations that are too large</td>
</tr>
<tr><td>ZeroDivisoinError</td>
<td>Division or modulo operation with zero is divisor</td>
</tr>
<tr><td>AssertionError</td>
<td>Used when an assert statement fails</td>
</tr>
<tr><td>AttributeError</td>
<td>Attribute reference or failure to assign correctly</td>
</tr>
<tr><td>EnvironmentError</td>
<td>An error occurred outside of Python</td>
</tr>
<tr><td>IOError</td>
<td>Error in Input/Output operation</td>
</tr>
<tr><td>OSError</td>
<td>An error occurred in the os module</td>
</tr>
<tr><td>EOFError</td>
<td>input() or raw_input() tried to read past the end of a file</td>
</tr>
<tr><td>ImportError</td>
<td>Import failed to find module or name</td>
</tr>
<tr><td>LookupError</td>
<td>Base class for IndexError and KeyError</td>
</tr>
<tr><td>IndexError</td>
<td>A sequence index goes out of range</td>
</tr>
<tr><td>KeyError</td>
<td>Referenced a non-existent mapping (dict) key</td>
</tr>
<tr><td>MemoryError</td>
<td>Memory exhausted</td>
</tr>
<tr><td>NameError</td>
<td>Failure to find a local or global name</td>
</tr>
<tr><td>UnboundLocalError</td>
<td>Unassigned local variable is referenced</td>
</tr>
<tr><td>ReferenceError</td>
<td>Attempt to access a garbage-collected object</td>
</tr>
<tr><td>RuntimeError</td>
<td>Obsolete catch-all error</td>
</tr>
<tr><td>NotImplementedError</td>
<td>Raised when a feature is not implemented</td>
</tr>
<tr><td>SyntaxError</td>
<td>Parser encountered a syntax error</td>
</tr>
<tr><td>IndentationError</td>
<td>Parser encountered an indentation issue</td>
</tr>
<tr><td>TabError</td>
<td>Incorrect mixture of tabs and spaces</td>
</tr>
<tr><td>SystemError</td>
<td>Non-fatal interpreter error</td>
</tr>
<tr><td>TypeError</td>
<td>Inappropriate type was passed to a built-in operator or function</td>
</tr>
<tr><td>ValueError</td>
<td>Argument error not covered by TypeError or a more precise error</td>
</tr>
<tr><td>Warning</td>
<td>Base for all warnings</td>
</tr>
</tbody>
</table>
<p>The <em>try-except-finally</em> block is used in Python programs to perform the exception-handling task.  Much like that of Java,
code that may or may not raise an exception should be placed in the <em>try</em> block.  Differently though, exceptions that may be
caught go into an <em>except</em> block much like the Java <em>catch</em> equivalent.  Any tasks that must be performed no matter if an exception
is thrown or not should go into the <em>finally</em> block.</p>
<p>try-except-finally Logic</p>
<div class="highlight-python"><pre>try:
    # perform some task that may raise an exception
except Exception, value:
    # perform some exception handling
finally:
    # perform tasks that must always be completed</pre>
</div>
<p>Python also offers an optional <em>else</em> clause to create the <em>try-except-else</em> logic.  This optional code placed inside the
<em>else</em> block is run if there are no exceptions found in the block.</p>
<p>try-finally logic:</p>
<div class="highlight-python"><pre>try:
    # perform some tasks that may raise an exception
finally:
    # perform tasks that must always be completed</pre>
</div>
<p>try-except-else logic:</p>
<div class="highlight-python"><pre>try:
    # perform some tasks that may raise an exception
except:
    # perform some exception handling
else:
    # perform some tasks that should only be performed if no exceptions are thrown</pre>
</div>
<p>You can name the specific type of exception to catch within the <em>except</em> block , or you can generically define an exception
handling block by not naming any exception at all.  Best practice of course states that you should always try to name
the exception and then provide the best possible handling solution for the case.  After all, if the program is simply
going to spit out a nasty error then the exception handling block does not help resolve the issue at all.  However, there
are some rare cases where it would be advantageous to not explicitly refer to an exception type when we simply wish to
ignore errors and move on.  The <em>except</em> block also allows us to define a variable to which the exception message will
be assigned.  This allows us the ability to store that message and display it somewhere within our exception handling code
block.  If you are calling a piece of Java code from within Jython and the Java code throws an exception, it can be handled
within Jython in the same manner as Jython exceptions.</p>
<p>Example 5-1:  Exception Handling in Python</p>
<div class="highlight-python"><pre># Code without an exception handler
&gt;&gt;&gt; x = 10
&gt;&gt;&gt; z = x / y
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
NameError: name 'y' is not defined

# The same code with an exception handling block
&gt;&gt;&gt; x = 10
&gt;&gt;&gt; try:
...     z = x / y
... except NameError, err:
...     print "One of the variables was undefined: ", err
...

One of the variables was undefined:  name 'y' is not defined</pre>
</div>
<p>Take note of the syntax that is being used for defining the variable that holds the error message.
Namely, the <em>except ExceptionType, value</em> statement syntax in Python and Jython 2.5 differs from that beyond 2.5.
In Python 2.6, the syntax changes a bit in order to ready developers for Python 3, which exclusively uses the new syntax.
Without going off topic too much, I think it is important to take note that this syntax will be changing in future
releases of Jython.</p>
<p>Jython and Python 2.5 and Prior</p>
<div class="highlight-python"><pre>try:
    // code
except ExceptionType, messageVar:
    // code</pre>
</div>
<p>Jython 2.6 (Not Yet Implemented) and Python 2.6 and Beyond</p>
<div class="highlight-python"><pre>try:
    // code
except ExceptionType as messageVar:
    // code</pre>
</div>
<p>We had previously mentioned that it was simply bad programming practice to not explicitly name an exception type
when writing exception handling code.  This is true, however Python provides us with another means to obtain the
type of exception that was thrown.  There is a function provided in the <em>sys</em> package known as <em>sys.exc_info()</em>
that will provide us with both the exception type and the exception message.  This can be quite useful if we are
wrapping some code in a <em>try-except</em> block but we really aren’t sure what type of exception may be thrown.  Below
is an example of using this technique.</p>
<p>Example 5-2:  Using sys.exc_info()</p>
<div class="highlight-python"><pre># Perform exception handling without explicitly naming the exception type
&gt;&gt;&gt; x = 10
&gt;&gt;&gt; try:
...     z = x / y
... except:
...     print "Unexpected error: ", sys.exc_info()[0], sys.exc_info()[1]
...
Unexpected error:  &lt;type 'exceptions.NameError'&gt; name 'y' is not defined</pre>
</div>
<p>Sometimes you may run into a situation where it is applicable to catch more than one exception.  Python offers a
couple of different options if you need to do such exception handling.  You can either use multiple <em>except­ clauses</em>,
which does the trick and works well, but may become too wordy.  The other option that you have is to enclose your
exception types within parentheses and separated by commas on your <em>except</em> statement.  Take a look at the following
example that portrays the latter approach using the same example from <em>Example 5-1.</em></p>
<p>Example 5-3:  Handling Multiple Exceptions</p>
<div class="highlight-python"><pre># Catch NameError, but also a ZeroDivisionError in case a zero is used in the equation
&gt;&gt;&gt; x = 10
&gt;&gt;&gt; try:
...     z = x / y
... except (NameError,ZeroDivisionError),  err:
...     print "One of the variables was undefined: ", err
...
One of the variables was undefined:  name 'y' is not defined


# Using mulitple except clauses
&gt;&gt;&gt; x = 10
&gt;&gt;&gt; y = 0
&gt;&gt;&gt; try:
...     z = x / y
... except NameError, err1:
...     print err1
... except ZeroDivisionError, err2:
...     print 'You cannot divide a number by zero!'
...
You cannot divide a number by zero!</pre>
</div>
<p>The <em>try-except­</em> block can be nested as deep as you’d like.  In the case of nested exception handling blocks,
if an exception is thrown then the program control will jump out of the inner most block that received the error,
and up to the block just above it.  This is very much the same type of action that is taken when you are working
in a nested loop and then run into a <em>break</em> statement, your code will stop executing and jump back up to the outer
loop.  The following example shows an example for such logic.</p>
<p>Example 5-4:  Nested Exception Handling Blocks</p>
<div class="highlight-python"><pre># Perform some division on numbers entered by keyboard
 try:
     # do some work
     try:
         x = raw_input ('Enter a number for the dividend:  ')
         y = raw_input('Enter a number to divisor: ')
         x = int(x)
         y = int(y)
     except ValueError, err2:
         # handle exception and move to outer try-except
         print 'You must enter a numeric value!'
     z = x / y
 except ZeroDivisionError, err1:
    # handle exception
     print 'You cannot divide by zero!'
 except TypeError, err3:
     print 'Retry and only use numeric values this time!'
 else:     print 'Your quotient is: %d' % (z)</pre>
</div>
</div>
<div class="section" id="raising-exceptions">
<h3>Raising Exceptions<a class="headerlink" href="#raising-exceptions" title="Permalink to this headline"></a></h3>
<p>Often times you will find reason to raise your own exceptions.  Maybe you are expecting a certain type
of keyboard entry, and a user enters something incorrectly that your program does not like.  This would
be a case when you’d like to raise your own exception.  The <em>raise</em> statement can be used to allow you to
raise an exception where you deem appropriate.  Using the <em>raise</em> statement, you can cause any of the Python
exception types to be raised, you could raise your own exception that you define (discussed in the next section),
or you could raise a string exception.  The <em>raise</em> statement is analogous to the <em>throw</em> statement in the
Java language.  In Java we may opt to throw an exception if necessary.  However, Java also allows you to
apply a <em>throws</em> clause to a particular method if an exception may possibly be thrown within instead of
using try-catch handler in the method.  Python does not allow you do perform such techniques using the
<em>raise</em> statement.</p>
<p>raise Statement Syntax</p>
<div class="highlight-python"><pre>raise ExceptionType or String[, message[, traceback]]</pre>
</div>
<p>As you can see from the syntax, using <em>raise</em> allows you to become creative in that you could use your own
string when raising an error.  However, this is not really looked upon as a best practice as you should try
to raise a defined exception type if at all possible.  You can also provide a short message explaining the
error.  This message can be any string.  Lastly, you can provide a <em>traceback</em> via use of <em>sys.exc_info()</em>.
Now you’ve surely seen some exceptions raised in the Python interpreter by now.  Each time an exception is
raised, a message appears that was created by the interpreter to give you feedback about the exception and
where the offending line of code may be.  There is always a <em>traceback</em> section when any exception is raised.
This really gives you more information on where the exception was raised.</p>
<p>Example 5-5: Using the raise Statement</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">raise</span> <span class="ne">TypeError</span><span class="p">,</span><span class="s">&quot;This is a special message&quot;</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n-Identifier">&lt;module&gt;</span>
<span class="nc">TypeError</span>: <span class="n-Identifier">This is a special message</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="defining-your-own-exceptions">
<h2>Defining Your Own Exceptions<a class="headerlink" href="#defining-your-own-exceptions" title="Permalink to this headline"></a></h2>
<p>You can define your own exceptions in Python by creating an exception class.  Now classes are a topic that
we have not yet covered, so this section gets a little ahead, but it is fairly straightforward.  You simply
define a class using the <em>class</em> keyword and then give it a name.  An exception class should inherit from
the base exception class, <em>Exception</em>.  The easiest defined exception can simply use a pass statement inside
the class.  More involved exception classes can accept parameters and define an initializer.  It is also
a good practice to name your exception giving it a suffix of <em>Error</em>.</p>
<p>Example 5-6: Defining an Exception Class</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">MyNewError</span><span class="p">(</span><span class="ne">Exception</span><span class="p">):</span>
    <span class="k">pass</span>
</pre></div>
</div>
<p>The example above is the simplest type of exception you can create.  This exception that was created above
can be raised just like any other exception now.</p>
<div class="highlight-python"><pre>raise MyNewError, “Something happened in my program”</pre>
</div>
<p>A more involved exception class may be written as follows.</p>
<p>Example 5-7: Exception Class Using Initializer</p>
<div class="highlight-python"><pre>class MegaError(Exception):
    “”” This is raised when there is a huge problem with my program”””
    def __init__(self, val):
        self.val = val
    def __str__(self):
        return repr(self.val)</pre>
</div>
</div>
<div class="section" id="issuing-warnings">
<h2>Issuing Warnings<a class="headerlink" href="#issuing-warnings" title="Permalink to this headline"></a></h2>
<p>Warnings can be raised at any time in your program and can be used to display some type of warning message,
but they do not necessarily cause execution to abort.  A good example is when you wish to deprecate a method
or implementation but still make it usable for compatibility.  You could create a warning to alert the user
and let them know that such methods are deprecated and point them to the new definition, but the program would
not abort.  Warnings are easy to define, but they can be complex if you wish to define rules on them using
filters.  Much like exceptions, there are a number of defined warnings that can be used for categorizing.  In
order to allow these warnings to be easily converted into exceptions, they are all instances of the <em>Exception</em>
type.</p>
<p>Table 5-2. Python Warning Categories</p>
<table border="1" class="docutils">
<colgroup>
<col width="24%" />
<col width="76%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">Warning</th>
<th class="head">Description</th>
</tr>
</thead>
<tbody valign="top">
<tr><td>Warning</td>
<td>Root warning class</td>
</tr>
<tr><td>UserWarning</td>
<td>A user-defined warning</td>
</tr>
<tr><td>DeprecationWarning</td>
<td>Warns about use of a deprecated feature</td>
</tr>
<tr><td>SyntaxWarning</td>
<td>Syntax issues</td>
</tr>
<tr><td>RuntimeWarning</td>
<td>Runtime issues</td>
</tr>
<tr><td>FutureWarning</td>
<td>Warns that a particular feature will be changing in a future release</td>
</tr>
</tbody>
</table>
<p>Table 5-1:  Exceptions</p>
<p>To issue a warning, you must first import the <em>warnings</em> module into your program.  Once this has been done
then it is as simple as making a call to the <em>warnings.warn()</em> function and passing it a string with the warning
message.  However, if you’d like to control the type of warning that is issued, you can also pass the warning
category.</p>
<div class="highlight-python"><pre>import warnings
warnings.warn(“this feature will be deprecated”)
warnings.warn(“this is a more involved warning”, RuntimeWarning)</pre>
</div>
<p>Importing the warnings module into your code gives you access to a number of built-in warning functions that can
be used.  If you’d like to filter a warning and change its behavior then you can do so by creating a filter.
The following is a list of functions that come with the <em>warnings</em> module.</p>
<table border="1" class="docutils">
<colgroup>
<col width="54%" />
<col width="46%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">Function and Description</th>
<th class="head">&nbsp;</th>
</tr>
</thead>
<tbody valign="top">
<tr><td>warn(message[, category[, stacklevel]])</td>
<td>Issues a warning.  Parameters include a message string,
the optional category of warning, and the optional
stacklevel that tells which stack frame the warning
should originate from.</td>
</tr>
<tr><td>warn_explicit(message, category, filename, lineno[, module[, registry]])</td>
<td>This offers a more detailed warning message and makes category
a mandatory parameter.  filename, lineno, and
module tell where the warning is located.  registry represents
all of the current warning filters that are active.</td>
</tr>
<tr><td>showwarning(message, category, filename, lineno[, file])</td>
<td>Gives you the ability to write the warning to a file.</td>
</tr>
<tr><td>formatwarning(message, category, filename, lineno)</td>
<td>Creates a formatted string representing the warning.</td>
</tr>
<tr><td>resetwarnings()</td>
<td>Resets all of the warning filters.</td>
</tr>
<tr><td>filterwarnings(action[, message[, category[, module[, lineno[, append]]]]])</td>
<td>&nbsp;</td>
</tr>
</tbody>
</table>
<p>This adds an entry into a warning filter list.  Warning filters allow you to modify the behavior of a warning.
The action in the warning filter can be one from the following table of actions, message is a regular expression,
category is the type of a warning to be issued, module can be a regular expression, lineno is a line number to
match against all lines, append specifies whether the filter should be appended to the list of all filters.</p>
<table border="1" class="docutils">
<colgroup>
<col width="27%" />
<col width="73%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">Filter Actions</th>
<th class="head">Description</th>
</tr>
</thead>
<tbody valign="top">
<tr><td>‘always’</td>
<td>Always print warning message</td>
</tr>
<tr><td>‘default’</td>
<td>Print warning once for each location where warning occurs</td>
</tr>
<tr><td>‘error’</td>
<td>Converts a warning into an exception</td>
</tr>
<tr><td>‘ignore’</td>
<td>Ignores the warning</td>
</tr>
<tr><td>‘module’</td>
<td>Print warning once for each module in which warning occurs</td>
</tr>
<tr><td>‘once’</td>
<td>Print warning only one time</td>
</tr>
</tbody>
</table>
<p>Table 5-3. Warning Functions</p>
<p>Warning filters are used to modify the behavior of a particular warning.  There can be many different warning filters
in use, and each call to the <em>filterwarnings()</em> function will append another warning to the list of filters if so desired.
In order to see which filters are currently in use, issue the command <em>print warnings.filters</em>.  One can also specify
a warning filter from the command line by use of the –W option.  Lastly, all warnings can be reset to defaults by using
the <em>resetwarnings()</em> function.:</p>
<div class="highlight-python"><pre>-Waction:message:category:module:lineno</pre>
</div>
</div>
<div class="section" id="assertions-and-debugging">
<h2>Assertions and Debugging<a class="headerlink" href="#assertions-and-debugging" title="Permalink to this headline"></a></h2>
<p>Debugging can be an easy task in Python via use of the <em>assert</em> statement and the <em>__debug__</em> variable.  Assertions
are statements that can print to indicate that a particular piece of code is not behaving as expected.  The assertion
checks an expression for a True or False value, and if False then it issues an <em>AssertionError</em> along with an optional
message.  If the expression evaluates to True then the assertion is ignored completely.</p>
<div class="highlight-python"><pre>assert expression [, message]</pre>
</div>
<p>By effectively using the <em>assert</em> statement throughout your program, you can easily catch any errors that may occur
and make debugging life much easier.  The following example will show you the use of the assert statement.:</p>
<div class="highlight-python"><pre>#  The following example shows how assertions are evaluated
&gt;&gt;&gt; x = 5
&gt;&gt;&gt; y = 10
&gt;&gt;&gt; assert x &lt; y, "The assertion is ignored"
&gt;&gt;&gt; assert x &gt; y, "The assertion works"
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
AssertionError: The assertion works</pre>
</div>
<p>You can make use of the internal ­­*­­__debug__* variable by placing entire blocks of code that should be run for debugging
purposes only inside a conditional based upon value of the variable.</p>
<p>Example 5-10: Making Use of __debug__</p>
<div class="highlight-python"><pre>if __debug__:
    # perform some debugging tasks</pre>
</div>
</div>
<div class="section" id="context-managers">
<h2>Context Managers<a class="headerlink" href="#context-managers" title="Permalink to this headline"></a></h2>
<p>Ensuring that code is written properly in order to manage resources such as files or database connections is an important
topic.  If files or database connections are opened and never closed then our program could incur issues.  Often times,
developers elect to make use of the issues.  Often times, developers elect to make use of the <em>try-finally</em> blocks to ensure
that such resources are handled properly.  While this is an acceptable method for resource management, it can sometimes
be misused and lead to problems when exceptions are raised in programs.  For instance, if we are working with a database
connection and an exception occurs after we’ve opened the connection, the program control may break out of the current block
and skip all further processing.  The connection may never be closed in such a case.  That is where the concept of context
management becomes an important new feature in Jython.  Context management via the use of the <em>with</em> statement is new to
Jython 2.5, and it is a very nice way to ensure that resources are managed as expected.</p>
<p>In order to use the <em>with</em> statement, you must import from __future__.  The <em>with</em> statement basically allows you to take
an object and use it without worrying about resource management.  For instance, let’s say that we’d like to open a file
on the system and read some lines from it.  To perform a file operation you first need to open the file, perform any
processing or reading of file content, and then close the file to free the resource.  Context management using the <em>with</em>
statement allows you to simply open the file and work with it in a concise syntax.</p>
<p>Example 5-11: Python with Statement Example</p>
<div class="highlight-python"><pre>#  Read from a text file named players.txt
&gt;&gt;&gt; from __future__ import with_statement
&gt;&gt;&gt; with open('players.txt','r') as file:
...     x = file.read()
...
&gt;&gt;&gt; print x
This is read from the file</pre>
</div>
<p>In the example above, we did not worry about closing the file because the context took care of that for us.  This works
with object that extends the context management protocol.  In other words, any object that implements two methods named
<em>__enter__()</em> and <em>__exit__()</em> adhere to the context management protocol.  When the <em>with *statement begins, the *__enter__()</em>
method is executed.  Likewise, as the last action performed when the <em>with</em> statement is ending, the <em>__exit__()</em>
method is executed.  The __enter__() method takes no arguments, whereas the __exit__() method takes three optional arguments
<em>type, value, *and</em> traceback.  <em>The *__exit__()</em> method returns a <em>True</em> or <em>False</em> value to indicate whether an exception
was thrown.  The <em>as variable</em> clause on the <em>with</em> statement is optional as it will allow you to make use of the object from
within the code block.  If you are working with resources such as a lock then you may not the optional clause.</p>
<p>If you follow the context management protocol, it is possible to create your own objects that can be used with this technique.
The <em>__enter__()</em> method should create whatever object you are trying to work if needed.  If you are working with an immutable
object then you’ll need to create a copy of that object to work with in the <em>__enter__()</em> method.  The <em>__exit__()</em> method
on the other hand can simply return <em>False</em> unless there is some other type of cleanup processing that needs to take place.</p>
</div>
<div class="section" id="summary">
<h2>Summary<a class="headerlink" href="#summary" title="Permalink to this headline"></a></h2>
<p>In this chapter, we discussed many different topics regarding exceptions and exception handling within a Python application.
First, you learned the exception handling syntax of the <em>try-except-finally</em> code block and how it is used.  We then discussed
why it may be important to <em>raise</em> your own exceptions at times and how to do so.  That topic led to the discussion of how
to define an exception and we learned that in order to do so we must define a class that extends the <em>Exception</em> type object.</p>
<p>After learning about exceptions, we went into the warnings framework and discussed how to use it.  It may be important to use
warnings in such cases where code may be deprecated and you want to warn users, but you do not wish to <em>raise</em> any exceptions.
That topic was followed by assertions and how assertion statement can be used to help us debug our programs.  Lastly, we touched
upon the topic of context managers and using the <em>with</em> statement that is new in Jython 2.5.</p>
<p>In the next chapter you will delve into creating classes and learning about object-oriented programming in Python.  Hopefully
if there were topics discussed in this chapter or previously in the book that may have been unclear due to unfamiliarity with
object orientation, they will be clarified in Chapter 6.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
            <h3><a href="index.html">Table Of Contents</a></h3>
            <ul>
<li><a class="reference external" href="">Chapter 5: Exception Handling and Debugging</a><ul>
<li><a class="reference external" href="#exception-handling-syntax-and-differences-with-java">Exception Handling Syntax and Differences with Java</a><ul>
<li><a class="reference external" href="#catching-exceptions">Catching Exceptions</a></li>
<li><a class="reference external" href="#raising-exceptions">Raising Exceptions</a></li>
</ul>
</li>
<li><a class="reference external" href="#defining-your-own-exceptions">Defining Your Own Exceptions</a></li>
<li><a class="reference external" href="#issuing-warnings">Issuing Warnings</a></li>
<li><a class="reference external" href="#assertions-and-debugging">Assertions and Debugging</a></li>
<li><a class="reference external" href="#context-managers">Context Managers</a></li>
<li><a class="reference external" href="#summary">Summary</a></li>
</ul>
</li>
</ul>

            <h4>Previous topic</h4>
            <p class="topless"><a href="chapter3.html"
                                  title="previous chapter">Chapter 3: Operators, Expressions, and Program Flow</a></p>
            <h4>Next topic</h4>
            <p class="topless"><a href="chapter6.html"
                                  title="next chapter">Chapter 6:  Object Oriented Jython</a></p>
            <h3>This Page</h3>
            <ul class="this-page-menu">
              <li><a href="_sources/chapter5.txt"
                     rel="nofollow">Show Source</a></li>
            </ul>
          <div id="searchbox" style="display: none">
            <h3>Quick search</h3>
              <form class="search" action="search.html" method="get">
                <input type="text" name="q" size="18" />
                <input type="submit" value="Go" />
                <input type="hidden" name="check_keywords" value="yes" />
                <input type="hidden" name="area" value="default" />
              </form>
              <p class="searchtip" style="font-size: 90%">
              Enter search terms or a module, class or function name.
              </p>
          </div>
          <script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="chapter6.html" title="Chapter 6: Object Oriented Jython"
             >next</a> |</li>
        <li class="right" >
          <a href="chapter3.html" title="Chapter 3: Operators, Expressions, and Program Flow"
             >previous</a> |</li>
        <li><a href="index.html">Jython Book v0.1 documentation</a> &raquo;</li> 
      </ul>
    </div>
    <div class="footer">
      &copy; Copyright 2009, Josh Juneau, Frank Wierzbicki, Jim Baker, Leo Soto, ViVictor Ng.
      Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 0.6.1.
    </div>
  </body>
</html>