Python Lab 9 : Exception Handling in Python

LAB 9 : Exception Handling in Python

<div class="whitepaper-body-page">

<p>When an error occurs, or exception as we call it, Python will normally stop and generate an error message.</p>



<p>These exceptions can be handled using the&nbsp;<code>try</code>&nbsp;statement</p>



<ul><li>The&nbsp;<code>try</code>&nbsp;block lets you test a block of code for errors.</li><li>The&nbsp;<code>except</code>&nbsp;block lets you handle the error.</li><li>The&nbsp;<code>finally</code>&nbsp;block lets you execute code, regardless of the result of the try- and except blocks.</li></ul>



<p>Example:This statement will raise an error, because&nbsp;<code>x</code>&nbsp;is not defined</p>



<div class="enlighter-default enlighter-v-standard enlighter-t-minimal enlighter-hover enlighter-linenumbers "><div class="enlighter-toolbar-top enlighter-toolbar"><div class="enlighter-btn enlighter-btn-raw" title="Plain text"></div><div class="enlighter-btn enlighter-btn-copy" title="Copy to clipboard"></div><div class="enlighter-btn enlighter-btn-window" title="Open code in new window"></div><div class="enlighter-btn enlighter-btn-website" title="EnlighterJS 3 Syntax Highlighter"></div></div><div class="enlighter" style=""><div class=""><div><span class="enlighter-m0">print</span><span class="enlighter-g1">(</span><span class="enlighter-text">x</span><span class="enlighter-g1">)</span></div></div></div><div class="enlighter-raw">print(x)</div><div class="enlighter-toolbar-bottom enlighter-toolbar"></div></div><pre class="EnlighterJSRAW enlighter-origin" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">print(x)</pre>



<div class="wp-block-pb-accordion-item c-accordion__item js-accordion-item" data-initially-open="false" data-click-to-close="true" data-auto-close="true" data-scroll="false" data-scroll-offset="0"><button id="at-53948" class="c-accordion__title js-accordion-controller c-accordion__title--button" role="button" tabindex="0" aria-controls="ac-53948" aria-expanded="false">Show Output</button><div id="ac-53948" class="c-accordion__content" hidden="hidden">
<pre class="wp-block-code"><code>Traceback (most recent call last):
  File &quot;&lt;pyshell#26&gt;&quot;, line 1, in &lt;module&gt;
    print(x)
NameError: name &#39;x&#39; is not defined</code></pre>



<p></p>
</div></div>



<p>The&nbsp;<code>try</code>&nbsp;block will generate an exception, because&nbsp;<code>x</code>&nbsp;is not defined.Since the try block raises an error, the except block will be executed.</p>



<div class="enlighter-default enlighter-v-standard enlighter-t-minimal enlighter-hover enlighter-linenumbers "><div class="enlighter-toolbar-top enlighter-toolbar"><div class="enlighter-btn enlighter-btn-raw" title="Plain text"></div><div class="enlighter-btn enlighter-btn-copy" title="Copy to clipboard"></div><div class="enlighter-btn enlighter-btn-window" title="Open code in new window"></div><div class="enlighter-btn enlighter-btn-website" title="EnlighterJS 3 Syntax Highlighter"></div></div><div class="enlighter" style=""><div class=""><div><span class="enlighter-k1">try</span><span class="enlighter-text">:</span></div></div><div class=""><div><span class="enlighter-text">  </span><span class="enlighter-m0">print</span><span class="enlighter-g1">(</span><span class="enlighter-text">x</span><span class="enlighter-g1">)</span><span class="enlighter-text"></span></div></div><div class=""><div><span class="enlighter-text"></span><span class="enlighter-k0">except</span><span class="enlighter-text">:</span></div></div><div class=""><div><span class="enlighter-text">  </span><span class="enlighter-m0">print</span><span class="enlighter-g1">(</span><span class="enlighter-s0">&quot;An exception occurred&quot;</span><span class="enlighter-g1">)</span></div></div></div><div class="enlighter-raw">try:
  print(x)
except:
  print(&quot;An exception occurred&quot;)</div><div class="enlighter-toolbar-bottom enlighter-toolbar"></div></div><pre class="EnlighterJSRAW enlighter-origin" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">try:
  print(x)
except:
  print(&quot;An exception occurred&quot;)</pre>



<div class="wp-block-pb-accordion-item c-accordion__item js-accordion-item" data-initially-open="false" data-click-to-close="true" data-auto-close="true" data-scroll="false" data-scroll-offset="0"><button id="at-69803" class="c-accordion__title js-accordion-controller c-accordion__title--button" role="button" tabindex="0" aria-controls="ac-69803" aria-expanded="false">Show Output</button><div id="ac-69803" class="c-accordion__content" hidden="hidden">
<pre class="wp-block-code"><code>An exception occurred</code></pre>
</div></div>



<h4 class="wp-block-heading">Many Exceptions</h4>



<p>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:</p>



<p>Example:Print one message if the try block raises a&nbsp;<code>NameError</code>&nbsp;and another for other errors:</p>



<div class="enlighter-default enlighter-v-standard enlighter-t-minimal enlighter-hover enlighter-linenumbers "><div class="enlighter-toolbar-top enlighter-toolbar"><div class="enlighter-btn enlighter-btn-raw" title="Plain text"></div><div class="enlighter-btn enlighter-btn-copy" title="Copy to clipboard"></div><div class="enlighter-btn enlighter-btn-window" title="Open code in new window"></div><div class="enlighter-btn enlighter-btn-website" title="EnlighterJS 3 Syntax Highlighter"></div></div><div class="enlighter" style=""><div class=""><div><span class="enlighter-k1">try</span><span class="enlighter-text">:</span></div></div><div class=""><div><span class="enlighter-text">  </span><span class="enlighter-m0">print</span><span class="enlighter-g1">(</span><span class="enlighter-text">x</span><span class="enlighter-g1">)</span><span class="enlighter-text"></span></div></div><div class=""><div><span class="enlighter-text"></span><span class="enlighter-k0">except</span><span class="enlighter-text"> NameError:</span></div></div><div class=""><div><span class="enlighter-text">  </span><span class="enlighter-m0">print</span><span class="enlighter-g1">(</span><span class="enlighter-s0">&quot;Variable x is not defined&quot;</span><span class="enlighter-g1">)</span><span class="enlighter-text"></span></div></div><div class=""><div><span class="enlighter-text"></span><span class="enlighter-k0">except</span><span class="enlighter-text">:</span></div></div><div class=""><div><span class="enlighter-text">  </span><span class="enlighter-m0">print</span><span class="enlighter-g1">(</span><span class="enlighter-s0">&quot;Something else went wrong&quot;</span><span class="enlighter-g1">)</span></div></div></div><div class="enlighter-raw">try:
  print(x)
except NameError:
  print(&quot;Variable x is not defined&quot;)
except:
  print(&quot;Something else went wrong&quot;)</div><div class="enlighter-toolbar-bottom enlighter-toolbar"></div></div><pre class="EnlighterJSRAW enlighter-origin" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">try:
  print(x)
except NameError:
  print(&quot;Variable x is not defined&quot;)
except:
  print(&quot;Something else went wrong&quot;)</pre>



<div class="wp-block-pb-accordion-item c-accordion__item js-accordion-item" data-initially-open="false" data-click-to-close="true" data-auto-close="true" data-scroll="false" data-scroll-offset="0"><button id="at-4469" class="c-accordion__title js-accordion-controller c-accordion__title--button" role="button" tabindex="0" aria-controls="ac-4469" aria-expanded="false">Show Output</button><div id="ac-4469" class="c-accordion__content" hidden="hidden">
<pre class="wp-block-code"><code>Variable x is not defined</code></pre>
</div></div>



<h4 class="wp-block-heading">Else Block</h4>



<p>You can use the&nbsp;<code>else</code>&nbsp;keyword to define a block of code to be executed if no errors were raised:</p>



<p>Example:In this example, the&nbsp;<code>try</code>&nbsp;block does not generate any error:</p>



<div class="enlighter-default enlighter-v-standard enlighter-t-minimal enlighter-hover enlighter-linenumbers "><div class="enlighter-toolbar-top enlighter-toolbar"><div class="enlighter-btn enlighter-btn-raw" title="Plain text"></div><div class="enlighter-btn enlighter-btn-copy" title="Copy to clipboard"></div><div class="enlighter-btn enlighter-btn-window" title="Open code in new window"></div><div class="enlighter-btn enlighter-btn-website" title="EnlighterJS 3 Syntax Highlighter"></div></div><div class="enlighter" style=""><div class=""><div><span class="enlighter-k1">try</span><span class="enlighter-text">:</span></div></div><div class=""><div><span class="enlighter-text">    x=</span><span class="enlighter-m0">int</span><span class="enlighter-g1">(</span><span class="enlighter-m0">input</span><span class="enlighter-g1">(</span><span class="enlighter-s0">&#39;enter any number:&#39;</span><span class="enlighter-g1">))</span><span class="enlighter-text"></span></div></div><div class=""><div><span class="enlighter-text">    y=</span><span class="enlighter-n1">100</span><span class="enlighter-text">/x       </span></div></div><div class=""><div><span class="enlighter-text"></span><span class="enlighter-k0">except</span><span class="enlighter-text"> ValueError:</span></div></div><div class=""><div><span class="enlighter-text">    </span><span class="enlighter-m0">print</span><span class="enlighter-g1">(</span><span class="enlighter-s0">&#39;Nothing entered&#39;</span><span class="enlighter-g1">)</span><span class="enlighter-text"></span></div></div><div class=""><div><span class="enlighter-text"></span><span class="enlighter-k0">except</span><span class="enlighter-text"> ZeroDivisionError:</span></div></div><div class=""><div><span class="enlighter-text">    </span><span class="enlighter-m0">print</span><span class="enlighter-g1">(</span><span class="enlighter-s0">&#39;enter any number other then Zero&#39;</span><span class="enlighter-g1">)</span><span class="enlighter-text"></span></div></div><div class=""><div><span class="enlighter-text"></span><span class="enlighter-k1">else</span><span class="enlighter-text">:</span></div></div><div class=""><div><span class="enlighter-text">    </span><span class="enlighter-m0">print</span><span class="enlighter-g1">(</span><span class="enlighter-text">y</span><span class="enlighter-g1">)</span></div></div></div><div class="enlighter-raw">try:
    x=int(input(&#39;enter any number:&#39;))
    y=100/x<br>except ValueError:
    print(&#39;Nothing entered&#39;)
except ZeroDivisionError:
    print(&#39;enter any number other then Zero&#39;)
else:
    print(y)</div><div class="enlighter-toolbar-bottom enlighter-toolbar"></div></div><pre class="EnlighterJSRAW enlighter-origin" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">try:
    x=int(input(&#39;enter any number:&#39;))
    y=100/x<br>except ValueError:
    print(&#39;Nothing entered&#39;)
except ZeroDivisionError:
    print(&#39;enter any number other then Zero&#39;)
else:
    print(y)</pre>



<div class="wp-block-pb-accordion-item c-accordion__item js-accordion-item" data-initially-open="false" data-click-to-close="true" data-auto-close="true" data-scroll="false" data-scroll-offset="0"><button id="at-84393" class="c-accordion__title js-accordion-controller c-accordion__title--button" role="button" tabindex="0" aria-controls="ac-84393" aria-expanded="false">Show Output</button><div id="ac-84393" class="c-accordion__content" hidden="hidden">
<pre class="wp-block-code"><code>enter any number:10
10.0</code></pre>
</div></div>



<h4 class="wp-block-heading">Finally Block</h4>



<p>The&nbsp;<code>finally</code>&nbsp;block, if specified, will be executed regardless if the try block raises an error or not.</p>



<div class="enlighter-default enlighter-v-standard enlighter-t-minimal enlighter-hover enlighter-linenumbers "><div class="enlighter-toolbar-top enlighter-toolbar"><div class="enlighter-btn enlighter-btn-raw" title="Plain text"></div><div class="enlighter-btn enlighter-btn-copy" title="Copy to clipboard"></div><div class="enlighter-btn enlighter-btn-window" title="Open code in new window"></div><div class="enlighter-btn enlighter-btn-website" title="EnlighterJS 3 Syntax Highlighter"></div></div><div class="enlighter" style=""><div class=""><div><span class="enlighter-k1">try</span><span class="enlighter-text">:</span></div></div><div class=""><div><span class="enlighter-text">    x=</span><span class="enlighter-m0">int</span><span class="enlighter-g1">(</span><span class="enlighter-m0">input</span><span class="enlighter-g1">(</span><span class="enlighter-s0">&#39;enter any number:&#39;</span><span class="enlighter-g1">))</span><span class="enlighter-text"></span></div></div><div class=""><div><span class="enlighter-text">    y=</span><span class="enlighter-n1">100</span><span class="enlighter-text">/x   </span></div></div><div class=""><div><span class="enlighter-text"></span><span class="enlighter-k0">except</span><span class="enlighter-text"> ValueError:</span></div></div><div class=""><div><span class="enlighter-text">    </span><span class="enlighter-m0">print</span><span class="enlighter-g1">(</span><span class="enlighter-s0">&#39;Nothing entered&#39;</span><span class="enlighter-g1">)</span><span class="enlighter-text"></span></div></div><div class=""><div><span class="enlighter-text"></span><span class="enlighter-k0">except</span><span class="enlighter-text"> ZeroDivisionError:</span></div></div><div class=""><div><span class="enlighter-text">    </span><span class="enlighter-m0">print</span><span class="enlighter-g1">(</span><span class="enlighter-s0">&#39;enter any number other then Zero&#39;</span><span class="enlighter-g1">)</span><span class="enlighter-text"></span></div></div><div class=""><div><span class="enlighter-text"></span><span class="enlighter-k1">else</span><span class="enlighter-text">:</span></div></div><div class=""><div><span class="enlighter-text">    </span><span class="enlighter-m0">print</span><span class="enlighter-g1">(</span><span class="enlighter-text">y</span><span class="enlighter-g1">)</span><span class="enlighter-text"></span></div></div><div class=""><div><span class="enlighter-text"></span><span class="enlighter-k1">finally</span><span class="enlighter-text">:</span></div></div><div class=""><div><span class="enlighter-text">    </span><span class="enlighter-m0">print</span><span class="enlighter-g1">(</span><span class="enlighter-s0">&#39;the try : except is finished&#39;</span><span class="enlighter-g1">)</span></div></div></div><div class="enlighter-raw">try:
    x=int(input(&#39;enter any number:&#39;))
    y=100/x<br>except ValueError:
    print(&#39;Nothing entered&#39;)
except ZeroDivisionError:
    print(&#39;enter any number other then Zero&#39;)
else:
    print(y)
finally:
    print(&#39;the try : except is finished&#39;)</div><div class="enlighter-toolbar-bottom enlighter-toolbar"></div></div><pre class="EnlighterJSRAW enlighter-origin" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">try:
    x=int(input(&#39;enter any number:&#39;))
    y=100/x<br>except ValueError:
    print(&#39;Nothing entered&#39;)
except ZeroDivisionError:
    print(&#39;enter any number other then Zero&#39;)
else:
    print(y)
finally:
    print(&#39;the try : except is finished&#39;)</pre>



<div class="wp-block-pb-accordion-item c-accordion__item js-accordion-item" data-initially-open="false" data-click-to-close="true" data-auto-close="true" data-scroll="false" data-scroll-offset="0"><button id="at-80646" class="c-accordion__title js-accordion-controller c-accordion__title--button" role="button" tabindex="0" aria-controls="ac-80646" aria-expanded="false">Show Output</button><div id="ac-80646" class="c-accordion__content" hidden="hidden">
<pre class="wp-block-code"><code>enter any number:0
enter any number other then Zero
the try : except is finished</code></pre>
</div></div>



<h4 class="wp-block-heading">Raise an exception</h4>



<p>As a Python developer you can choose to throw an exception if a condition occurs.To throw (or raise) an exception, use the&nbsp;<code>raise</code>&nbsp;keyword.</p>



<p>Example:Raise an error and stop the program if x is lower than 0</p>



<div class="enlighter-default enlighter-v-standard enlighter-t-minimal enlighter-hover enlighter-linenumbers "><div class="enlighter-toolbar-top enlighter-toolbar"><div class="enlighter-btn enlighter-btn-raw" title="Plain text"></div><div class="enlighter-btn enlighter-btn-copy" title="Copy to clipboard"></div><div class="enlighter-btn enlighter-btn-window" title="Open code in new window"></div><div class="enlighter-btn enlighter-btn-website" title="EnlighterJS 3 Syntax Highlighter"></div></div><div class="enlighter" style=""><div class=""><div><span class="enlighter-text">x = </span><span class="enlighter-n1">-1</span><span class="enlighter-text"></span></div></div><div class=""><div><span class="enlighter-text"></span><span class="enlighter-k1">if</span><span class="enlighter-text"> x </span><span class="enlighter-g1">&lt;</span><span class="enlighter-text"> </span><span class="enlighter-n1">0</span><span class="enlighter-text">:</span></div></div><div class=""><div><span class="enlighter-text">  </span><span class="enlighter-k1">raise</span><span class="enlighter-text"> </span><span class="enlighter-m0">Exception</span><span class="enlighter-g1">(</span><span class="enlighter-s0">&quot;Sorry, no numbers below zero&quot;</span><span class="enlighter-g1">)</span></div></div></div><div class="enlighter-raw">x = -1
if x &lt; 0:
  raise Exception(&quot;Sorry, no numbers below zero&quot;)</div><div class="enlighter-toolbar-bottom enlighter-toolbar"></div></div><pre class="EnlighterJSRAW enlighter-origin" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">x = -1
if x &lt; 0:
  raise Exception(&quot;Sorry, no numbers below zero&quot;)</pre>



<div class="wp-block-pb-accordion-item c-accordion__item js-accordion-item" data-initially-open="false" data-click-to-close="true" data-auto-close="true" data-scroll="false" data-scroll-offset="0"><button id="at-85954" class="c-accordion__title js-accordion-controller c-accordion__title--button" role="button" tabindex="0" aria-controls="ac-85954" aria-expanded="false">Show Output</button><div id="ac-85954" class="c-accordion__content" hidden="hidden">
<pre class="wp-block-code"><code>Traceback (most recent call last):
  File &quot;C:/Users/Pallavi/AppData/Local/Programs/Python/Python36/my programs/new module.py&quot;, line 3, in &lt;module&gt;
    raise Exception(&quot;Sorry, no numbers below zero&quot;)
Exception: Sorry, no numbers below zero</code></pre>
</div></div>



<p>The&nbsp;<code>raise</code>&nbsp;keyword is used to raise an exception.</p>



<p>You can define what kind of error to raise, and the text to print to the user.</p>



<p>Example:Raise a TypeError if x is not a string</p>



<div class="enlighter-default enlighter-v-standard enlighter-t-minimal enlighter-hover enlighter-linenumbers "><div class="enlighter-toolbar-top enlighter-toolbar"><div class="enlighter-btn enlighter-btn-raw" title="Plain text"></div><div class="enlighter-btn enlighter-btn-copy" title="Copy to clipboard"></div><div class="enlighter-btn enlighter-btn-window" title="Open code in new window"></div><div class="enlighter-btn enlighter-btn-website" title="EnlighterJS 3 Syntax Highlighter"></div></div><div class="enlighter" style=""><div class=""><div><span class="enlighter-text">x = </span><span class="enlighter-n1">35</span><span class="enlighter-text"></span></div></div><div class=""><div><span class="enlighter-text"></span><span class="enlighter-k1">if</span><span class="enlighter-text"> </span><span class="enlighter-m0">type</span><span class="enlighter-g1">(</span><span class="enlighter-text">x</span><span class="enlighter-g1">)</span><span class="enlighter-text">!=str:</span></div></div><div class=""><div><span class="enlighter-text">    </span><span class="enlighter-k1">raise</span><span class="enlighter-text"> </span><span class="enlighter-m0">Exception</span><span class="enlighter-g1">(</span><span class="enlighter-s0">&quot;Only strings are allowed&quot;</span><span class="enlighter-g1">)</span></div></div></div><div class="enlighter-raw">x = 35
if type(x)!=str:
    raise Exception(&quot;Only strings are allowed&quot;)</div><div class="enlighter-toolbar-bottom enlighter-toolbar"></div></div><pre class="EnlighterJSRAW enlighter-origin" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">x = 35
if type(x)!=str:
    raise Exception(&quot;Only strings are allowed&quot;)</pre>



<div class="wp-block-pb-accordion-item c-accordion__item js-accordion-item" data-initially-open="false" data-click-to-close="true" data-auto-close="true" data-scroll="false" data-scroll-offset="0"><button id="at-54771" class="c-accordion__title js-accordion-controller c-accordion__title--button" role="button" tabindex="0" aria-controls="ac-54771" aria-expanded="false">Show Output</button><div id="ac-54771" class="c-accordion__content" hidden="hidden">
<pre class="wp-block-code"><code>Traceback (most recent call last):
  File &quot;C:/Users/Pallavi/AppData/Local/Programs/Python/Python36/my programs/new module.py&quot;, line 3, in &lt;module&gt;
    raise Exception(&quot;Only strings are allowed&quot;)
Exception: Only strings are allowed</code></pre>
</div></div>

<p></div></p>