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 <code>try</code> statement</p>
<ul><li>The <code>try</code> block lets you test a block of code for errors.</li><li>The <code>except</code> block lets you handle the error.</li><li>The <code>finally</code> 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 <code>x</code> 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 "<pyshell#26>", line 1, in <module>
print(x)
NameError: name 'x' is not defined</code></pre>
<p></p>
</div></div>
<p>The <code>try</code> block will generate an exception, because <code>x</code> 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">"An exception occurred"</span><span class="enlighter-g1">)</span></div></div></div><div class="enlighter-raw">try:
print(x)
except:
print("An exception occurred")</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("An exception occurred")</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 <code>NameError</code> 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">"Variable x is not defined"</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">"Something else went wrong"</span><span class="enlighter-g1">)</span></div></div></div><div class="enlighter-raw">try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")</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("Variable x is not defined")
except:
print("Something else went wrong")</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 <code>else</code> keyword to define a block of code to be executed if no errors were raised:</p>
<p>Example:In this example, the <code>try</code> 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">'enter any number:'</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">'Nothing entered'</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">'enter any number other then Zero'</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('enter any number:'))
y=100/x<br>except ValueError:
print('Nothing entered')
except ZeroDivisionError:
print('enter any number other then Zero')
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('enter any number:'))
y=100/x<br>except ValueError:
print('Nothing entered')
except ZeroDivisionError:
print('enter any number other then Zero')
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 <code>finally</code> 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">'enter any number:'</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">'Nothing entered'</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">'enter any number other then Zero'</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">'the try : except is finished'</span><span class="enlighter-g1">)</span></div></div></div><div class="enlighter-raw">try:
x=int(input('enter any number:'))
y=100/x<br>except ValueError:
print('Nothing entered')
except ZeroDivisionError:
print('enter any number other then Zero')
else:
print(y)
finally:
print('the try : except is finished')</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('enter any number:'))
y=100/x<br>except ValueError:
print('Nothing entered')
except ZeroDivisionError:
print('enter any number other then Zero')
else:
print(y)
finally:
print('the try : except is finished')</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 <code>raise</code> 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"><</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">"Sorry, no numbers below zero"</span><span class="enlighter-g1">)</span></div></div></div><div class="enlighter-raw">x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")</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 < 0:
raise Exception("Sorry, no numbers below zero")</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 "C:/Users/Pallavi/AppData/Local/Programs/Python/Python36/my programs/new module.py", line 3, in <module>
raise Exception("Sorry, no numbers below zero")
Exception: Sorry, no numbers below zero</code></pre>
</div></div>
<p>The <code>raise</code> 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">"Only strings are allowed"</span><span class="enlighter-g1">)</span></div></div></div><div class="enlighter-raw">x = 35
if type(x)!=str:
raise Exception("Only strings are allowed")</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("Only strings are allowed")</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 "C:/Users/Pallavi/AppData/Local/Programs/Python/Python36/my programs/new module.py", line 3, in <module>
raise Exception("Only strings are allowed")
Exception: Only strings are allowed</code></pre>
</div></div>
<p></div></p>