<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Exception Handling - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Exception Handling - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Thu, 28 May 2026 20:57:42 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/exception-handling/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Try Catch: Exception Handling Explained ]]>
                </title>
                <description>
                    <![CDATA[ The try...catch..finally statement specifies a block of code to try along with a response should an error occur. The try statement contains one or more try blocks, and ends with at least one catch and/or a finally clause. try...catch: try {    throw ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/error-handling-and-try-catch-throw/</link>
                <guid isPermaLink="false">66c349c5a7aea9fc97bdfb14</guid>
                
                    <category>
                        <![CDATA[ Exception Handling ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sun, 26 Jan 2020 17:19:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9d85740569d1a4ca3834.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The <code>try...catch..finally</code> statement specifies a block of code to try along with a response should an error occur. The <code>try</code> statement contains one or more <code>try</code> blocks, and ends with at least one <code>catch</code> and/or a <code>finally</code> clause.</p>
<h3 id="heading-trycatch"><code>try...catch</code>:</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">try</span> {
   <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'my error'</span>);
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-built_in">console</span>.error(err.message);
}

<span class="hljs-comment">// Output: my error</span>
</code></pre>
<h3 id="heading-tryfinally"><code>try...finally</code>:</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">try</span> {
   <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'my error'</span>);
} <span class="hljs-keyword">finally</span> {
  <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'finally'</span>);
}

<span class="hljs-comment">// Output: finally</span>
</code></pre>
<p>When you don't use a <code>catch</code> statement, the error is not "caught", even though the code in the <code>finally</code> block is executed. Instead, the error will continue to the upper <code>try</code> block (or main block).</p>
<h3 id="heading-trycatchfinally"><code>try...catch...finally</code>:</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">try</span> {
   <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'my error'</span>);
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-built_in">console</span>.error(err.message);
} <span class="hljs-keyword">finally</span> {
  <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'finally'</span>);
}

<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// my error</span>
<span class="hljs-comment">// finally</span>
</code></pre>
<p><strong>Typical usage:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">try</span> {
   openFile(file);
   readFile(file)
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-built_in">console</span>.error(err.message);
} <span class="hljs-keyword">finally</span> {
  closeFile(file);
}
</code></pre>
<h3 id="heading-nested-trycatch">Nested <code>try...catch</code>:</h3>
<p>You can also:</p>
<ul>
<li>Nest a <code>try-catch</code> statement inside a <code>try</code> block.</li>
</ul>
<p>You can nest a <code>try...catch</code> statement within a <code>try</code> block. For example, to throw an error upwards:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">try</span> {
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'my error'</span>);
  } <span class="hljs-keyword">catch</span> (err) {
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'inner'</span>, err.message);
    <span class="hljs-keyword">throw</span> err;
  } <span class="hljs-keyword">finally</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'inner finally'</span>);
  }
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'outer'</span>, err.message);
}

<span class="hljs-comment">// Output: </span>
<span class="hljs-comment">// inner my error </span>
<span class="hljs-comment">// inner finally </span>
<span class="hljs-comment">// outer my error</span>
</code></pre>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Handle Exceptions in Python: A Detailed Visual Introduction ]]>
                </title>
                <description>
                    <![CDATA[ Welcome! In this article, you will learn how to handle exceptions in Python. In particular, we will cover: Exceptions The purpose of exception handling The try clause The except clause The else clause The finally clause How to raise exceptions Are ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/exception-handling-python/</link>
                <guid isPermaLink="false">66b1f83132a6794893871309</guid>
                
                    <category>
                        <![CDATA[ Exception Handling ]]>
                    </category>
                
                    <category>
                        <![CDATA[ learning to code ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Estefania Cassingena Navone ]]>
                </dc:creator>
                <pubDate>Sun, 22 Dec 2019 15:27:27 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/12/Exception-Handling-in-Python.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Welcome! In this article, you will learn how to handle exceptions in Python.</p>
<p><strong>In particular, we will cover:</strong></p>
<ul>
<li>Exceptions</li>
<li>The purpose of exception handling</li>
<li>The try clause</li>
<li>The except clause</li>
<li>The else clause</li>
<li>The finally clause</li>
<li>How to raise exceptions</li>
</ul>
<p><strong>Are you ready? Let's begin! 😀</strong></p>
<h2 id="heading-1-intro-to-exceptions">1️⃣ Intro to Exceptions</h2>
<p>We will start with exceptions:</p>
<ul>
<li><strong>What</strong> are they? </li>
<li><strong>Why</strong> are they relevant? </li>
<li><strong>Why</strong> should you handle them?</li>
</ul>
<p>According to the <a target="_blank" href="https://docs.python.org/3/tutorial/errors.html#exceptions">Python documentation</a>:</p>
<blockquote>
<p>Errors detected during execution are called <strong><em>exceptions</em></strong> and are not unconditionally fatal.</p>
</blockquote>
<p><strong>Exceptions are raised when the program encounters an error during its execution.</strong> They disrupt the normal flow of the program and usually end it abruptly. To avoid this, you can catch them and handle them appropriately.</p>
<p>You've probably seen them during your programming projects. </p>
<p>If you've ever tried to divide by zero in Python, you must have seen this error message:</p>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span>a = <span class="hljs-number">5</span>/<span class="hljs-number">0</span>
Traceback (most recent call last):
  File <span class="hljs-string">"&lt;pyshell#1&gt;"</span>, line <span class="hljs-number">1</span>, <span class="hljs-keyword">in</span> &lt;module&gt;
    a = <span class="hljs-number">5</span>/<span class="hljs-number">0</span>
ZeroDivisionError: division by zero
</code></pre>
<p>If you tried to index a string with an invalid index, you definitely got this error message:</p>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span>a = <span class="hljs-string">"Hello, World"</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>a[<span class="hljs-number">456</span>]
Traceback (most recent call last):
  File <span class="hljs-string">"&lt;pyshell#3&gt;"</span>, line <span class="hljs-number">1</span>, <span class="hljs-keyword">in</span> &lt;module&gt;
    a[<span class="hljs-number">456</span>]
IndexError: string index out of range
</code></pre>
<p>These are examples of exceptions.</p>
<h3 id="heading-common-exceptions">🔹 Common Exceptions</h3>
<p>There are many different types of exceptions, and they are all raised in particular situations. Some of the exceptions that you will most likely see as you work on your projects are:</p>
<ul>
<li><strong>IndexError</strong> - raised when you try to index a list, tuple, or string beyond the permitted boundaries. For example:</li>
</ul>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span>num = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">6</span>, <span class="hljs-number">5</span>]
<span class="hljs-meta">&gt;&gt;&gt; </span>num[<span class="hljs-number">56546546</span>]
Traceback (most recent call last):
  File <span class="hljs-string">"&lt;pyshell#7&gt;"</span>, line <span class="hljs-number">1</span>, <span class="hljs-keyword">in</span> &lt;module&gt;
    num[<span class="hljs-number">56546546</span>]
IndexError: list index out of range
</code></pre>
<ul>
<li><strong>KeyError</strong> - raised when you try to access the value of a key that doesn't exist in a dictionary. For example:</li>
</ul>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span>students = {<span class="hljs-string">"Nora"</span>: <span class="hljs-number">15</span>, <span class="hljs-string">"Gino"</span>: <span class="hljs-number">30</span>}
<span class="hljs-meta">&gt;&gt;&gt; </span>students[<span class="hljs-string">"Lisa"</span>]
Traceback (most recent call last):
  File <span class="hljs-string">"&lt;pyshell#9&gt;"</span>, line <span class="hljs-number">1</span>, <span class="hljs-keyword">in</span> &lt;module&gt;
    students[<span class="hljs-string">"Lisa"</span>]
KeyError: <span class="hljs-string">'Lisa'</span>
</code></pre>
<ul>
<li><strong>NameError</strong> - raised when a name that you are referencing in the code doesn't exist. For example:</li>
</ul>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span>a = b
Traceback (most recent call last):
  File <span class="hljs-string">"&lt;pyshell#10&gt;"</span>, line <span class="hljs-number">1</span>, <span class="hljs-keyword">in</span> &lt;module&gt;
    a = b
NameError: name <span class="hljs-string">'b'</span> <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> defined
</code></pre>
<ul>
<li><strong>TypeError</strong> - raised when an operation or function is applied to an object of an inappropriate type. For example:</li>
</ul>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span>(<span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>) * (<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
Traceback (most recent call last):
  File <span class="hljs-string">"&lt;pyshell#12&gt;"</span>, line <span class="hljs-number">1</span>, <span class="hljs-keyword">in</span> &lt;module&gt;
    (<span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>) * (<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
TypeError: can<span class="hljs-string">'t multiply sequence by non-int of type '</span>tuple<span class="hljs-string">'</span>
</code></pre>
<ul>
<li><strong>ZeroDivisionError</strong> - raised when you try to divide by zero.</li>
</ul>
<pre><code class="lang-python"><span class="hljs-meta">&gt;&gt;&gt; </span>a = <span class="hljs-number">5</span>/<span class="hljs-number">0</span>
Traceback (most recent call last):
  File <span class="hljs-string">"&lt;pyshell#13&gt;"</span>, line <span class="hljs-number">1</span>, <span class="hljs-keyword">in</span> &lt;module&gt;
    a = <span class="hljs-number">5</span>/<span class="hljs-number">0</span>
ZeroDivisionError: division by zero
</code></pre>
<p>💡 <strong>Tips:</strong> To learn more about other types of built-in exceptions, please <a target="_blank" href="https://docs.python.org/3/library/exceptions.html">refer to this article</a> in the Python Documentation.</p>
<h3 id="heading-anatomy-of-an-exception">🔸 <strong>Anatomy of an Exception</strong></h3>
<p>I'm sure that you must have noticed a general pattern in these error messages. Let's break down their general structure piece by piece:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/12/image-8.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>First, we find this line (see below). A <strong>traceback</strong> is basically a list detailing the function calls that were made before the exception was raised. </p>
<p>The traceback helps you during the debugging process because you can analyze the sequence of function calls that resulted in the exception:</p>
<pre><code class="lang-python">Traceback (most recent call last):
</code></pre>
<p>Then, we see this line (see below) with the path to the file and the line that raised the exception. In this case, the path was the Python shell  since the example was executed directly in IDLE.</p>
<pre><code class="lang-python">File <span class="hljs-string">"&lt;pyshell#0&gt;"</span>, line <span class="hljs-number">1</span>, <span class="hljs-keyword">in</span> &lt;module&gt;
   a - <span class="hljs-number">5</span>/<span class="hljs-number">0</span>
</code></pre>
<p><strong>💡 Tip:</strong> If the line that raised the exception belongs to a function,   is replaced by the name of the function.</p>
<p>Finally, we see a descriptive message detailing the type of exception and providing additional information to help us debug the code:</p>
<pre><code>NameError: name <span class="hljs-string">'a'</span> is not defined
</code></pre><h2 id="heading-2-exception-handling-purpose-amp-context">2️⃣ Exception Handling: Purpose &amp; Context</h2>
<p>You may ask: why would I want to handle exceptions? Why is this helpful for me? By handling exceptions, you can provide an alternative flow of execution to avoid crashing your program unexpectedly.</p>
<h3 id="heading-example-user-input">🔹 Example: User Input</h3>
<p>Imagine what would happen if a user who is working with your program enters an invalid input. This would raise an exception because an invalid operation was performed during the process. </p>
<p>If your program doesn't handle this correctly, it will crash suddenly and the user will have a very disappointing experience with your product.</p>
<p><strong>But if you do handle the exception, you will be able to provide an alternative to improve the experience of the user.</strong> </p>
<p>Perhaps you could display a descriptive message asking the user to enter a valid input, or you could provide a default value for the input. Depending on the context, you can choose what to do when this happens, and this is the magic of error handling. It can save the day when unexpected things happen. ⭐️</p>
<h3 id="heading-what-happens-behind-the-scenes">🔸 What Happens Behind the Scenes?</h3>
<p>Basically, when we handle an exception, we are telling the program what to do if the exception is raised. In that case, the "alternative" flow of execution will come to the rescue. If no exceptions are raised, the code will run as expected.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/12/image-10.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-3-time-to-code-the-try-except-statement">3️⃣ Time to Code: The try ... except Statement</h2>
<p>Now that you know what exceptions are and why you should we handle them, we will start diving into the built-in tools that the Python languages offers for this purpose. </p>
<p><strong>First, we have the most basic statement: try ... except.</strong></p>
<p>Let's illustrate this with a simple example. We have this small program that asks the user to enter the name of a student to display his/her age:</p>
<pre><code class="lang-python">students = {<span class="hljs-string">"Nora"</span>: <span class="hljs-number">15</span>, <span class="hljs-string">"Gino"</span>: <span class="hljs-number">30</span>}

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">print_student_age</span>():</span>
    name = input(<span class="hljs-string">"Please enter the name of the student: "</span>)
    print(students[name])

print_student_age()
</code></pre>
<p>Notice how we are not validating user input at the moment, so the user might enter invalid values (names that are not in the dictionary) and the consequences would be catastrophic because the program would crash if a KeyError is raised:</p>
<pre><code class="lang-python"><span class="hljs-comment"># User Input</span>
Please enter the name of the student: <span class="hljs-string">"Daniel"</span>

<span class="hljs-comment"># Error Message</span>
Traceback (most recent call last):
  File <span class="hljs-string">"&lt;path&gt;"</span>, line <span class="hljs-number">15</span>, <span class="hljs-keyword">in</span> &lt;module&gt;
    print_student_age()
  File <span class="hljs-string">"&lt;path&gt;"</span>, line <span class="hljs-number">13</span>, <span class="hljs-keyword">in</span> print_student_age
    print(students[name])
KeyError: <span class="hljs-string">'"Daniel"'</span>
</code></pre>
<h3 id="heading-syntax">🔹 Syntax</h3>
<p>We can handle this nicely using try ... except. This is the basic syntax:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/12/image-11.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In our example, we would add the try ... except statement within the function. Let's break this down piece by piece:</p>
<pre><code class="lang-python">students = {<span class="hljs-string">"Nora"</span>: <span class="hljs-number">15</span>, <span class="hljs-string">"Gino"</span>: <span class="hljs-number">30</span>}

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">print_student_age</span>():</span>
    <span class="hljs-keyword">while</span> <span class="hljs-literal">True</span>:
        <span class="hljs-keyword">try</span>:
            name = input(<span class="hljs-string">"Please enter the name of the student: "</span>)
            print(students[name])
            <span class="hljs-keyword">break</span>
        <span class="hljs-keyword">except</span>:
            print(<span class="hljs-string">"This name is not registered"</span>)


print_student_age()
</code></pre>
<p>If we "zoom in", we see the try ... except statement:</p>
<pre><code><span class="hljs-keyword">try</span>:
    name = input(<span class="hljs-string">"Please enter the name of the student: "</span>)
    print(students[name])
    <span class="hljs-keyword">break</span>
<span class="hljs-attr">except</span>:
    print(<span class="hljs-string">"This name is not registered"</span>)
</code></pre><ul>
<li>When the function is called, the try clause will run. If no exceptions are raised, the program will run as expected. </li>
<li>But if an exception is raised in the try clause, the flow of execution will immediately jump to the except clause to handle the exception.</li>
</ul>
<p><strong>💡 Note:</strong> This code is contained within a while loop to continue asking for user input if the value is invalid. This is an example:</p>
<pre><code class="lang-python">Please enter the name of the student: <span class="hljs-string">"Lulu"</span>
This name <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> registered
Please enter the name of the student:
</code></pre>
<p>This is great, right? Now we can continue asking for user input if the value is invalid. </p>
<p>At the moment, we are handling all possible exceptions with the same except clause. But what if we only want to handle a specific type of exception? Let's see how we could do this.</p>
<h3 id="heading-catching-specific-exceptions">🔸 Catching Specific Exceptions</h3>
<p>Since not all types of exceptions are handled in the same way, we can specify which exceptions we would like to handle with this syntax:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/12/image-15.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This is an example. We are handling the ZeroDivisionError exception in case the user enters zero as the denominator:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">divide_integers</span>():</span>
    <span class="hljs-keyword">while</span> <span class="hljs-literal">True</span>:
        <span class="hljs-keyword">try</span>:
            a = int(input(<span class="hljs-string">"Please enter the numerator: "</span>))
            b = int(input(<span class="hljs-string">"Please enter the denominator: "</span>))
            print(a / b)
        <span class="hljs-keyword">except</span> ZeroDivisionError:
            print(<span class="hljs-string">"Please enter a valid denominator."</span>)


divide_integers()
</code></pre>
<p>This would be the result:</p>
<pre><code class="lang-python"><span class="hljs-comment"># First iteration</span>
Please enter the numerator: <span class="hljs-number">5</span>
Please enter the denominator: <span class="hljs-number">0</span>
Please enter a valid denominator. 

<span class="hljs-comment"># Second iteration</span>
Please enter the numerator: <span class="hljs-number">5</span>
Please enter the denominator: <span class="hljs-number">2</span>
<span class="hljs-number">2.5</span>
</code></pre>
<p>We are handling this correctly. But... if another type of exception is raised, the program will not handle it gracefully. </p>
<p>Here we have an example of a ValueError because one of the values is a float, not an int:</p>
<pre><code class="lang-python">Please enter the numerator: <span class="hljs-number">5</span>
Please enter the denominator: <span class="hljs-number">0.5</span>
Traceback (most recent call last):
  File <span class="hljs-string">"&lt;path&gt;"</span>, line <span class="hljs-number">53</span>, <span class="hljs-keyword">in</span> &lt;module&gt;
    divide_integers()
  File <span class="hljs-string">"&lt;path&gt;"</span>, line <span class="hljs-number">47</span>, <span class="hljs-keyword">in</span> divide_integers
    b = int(input(<span class="hljs-string">"Please enter the denominator: "</span>))
ValueError: invalid literal <span class="hljs-keyword">for</span> int() <span class="hljs-keyword">with</span> base <span class="hljs-number">10</span>: <span class="hljs-string">'0.5'</span>
</code></pre>
<p>We can customize how we handle different types of exceptions.</p>
<h3 id="heading-multiple-except-clauses">🔹 Multiple Except Clauses</h3>
<p>To do this, we need to add multiple <code>except</code> clauses to handle different types of exceptions differently. </p>
<p>According to the <a target="_blank" href="https://docs.python.org/3/tutorial/errors.html#handling-exceptions">Python Documentation</a>:</p>
<blockquote>
<p>A try statement may have <strong>more than one except clause</strong>, to specify handlers for different exceptions. <strong>At most one handler will be executed</strong>.</p>
</blockquote>
<p>In this example, we have two except clauses. One of them handles ZeroDivisionError and the other one handles ValueError, the two types of exceptions that could be raised in this try block. </p>
<pre><code>def divide_integers():
    <span class="hljs-keyword">while</span> True:
        <span class="hljs-keyword">try</span>:
            a = int(input(<span class="hljs-string">"Please enter the numerator: "</span>))
            b = int(input(<span class="hljs-string">"Please enter the denominator: "</span>))
            print(a / b)
        except ZeroDivisionError:
            print(<span class="hljs-string">"Please enter a valid denominator."</span>)
        except ValueError:
            print(<span class="hljs-string">"Both values have to be integers."</span>)


divide_integers()
</code></pre><p>💡 <strong>Tip:</strong> You have to determine which types of exceptions might be raised in the try block to handle them appropriately.</p>
<h3 id="heading-multiple-exceptions-one-except-clause">🔸 Multiple Exceptions, One Except Clause</h3>
<p>You can also choose to handle different types of exceptions with the same except clause. </p>
<p>According to the <a target="_blank" href="https://docs.python.org/3/tutorial/errors.html#handling-exceptions">Python Documentation</a>:</p>
<blockquote>
<p>An except clause may name <strong>multiple exceptions</strong> as a parenthesized tuple.</p>
</blockquote>
<p>This is an example where we catch two exceptions (ZeroDivisionError and ValueError) with the same <code>except</code> clause:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">divide_integers</span>():</span>
    <span class="hljs-keyword">while</span> <span class="hljs-literal">True</span>:
        <span class="hljs-keyword">try</span>:
            a = int(input(<span class="hljs-string">"Please enter the numerator: "</span>))
            b = int(input(<span class="hljs-string">"Please enter the denominator: "</span>))
            print(a / b)
        <span class="hljs-keyword">except</span> (ZeroDivisionError, ValueError):
            print(<span class="hljs-string">"Please enter valid integers."</span>)

divide_integers()
</code></pre>
<p>The output would be the same for the two types of exceptions because they are handled by the same except clause:</p>
<pre><code class="lang-python">Please enter the numerator: <span class="hljs-number">5</span>
Please enter the denominator: <span class="hljs-number">0</span>
Please enter valid integers.
</code></pre>
<pre><code class="lang-python">Please enter the numerator: <span class="hljs-number">0.5</span>
Please enter valid integers.
Please enter the numerator:
</code></pre>
<h3 id="heading-handling-exceptions-raised-by-functions-called-in-the-try-clause">🔹 Handling Exceptions Raised by Functions Called in the try Clause</h3>
<p>An interesting aspect of exception handling is that if an exception is raised in a function that was previously called in the try clause of another function and the function itself does not handle it, the caller will handle it if there is an appropriate except clause. </p>
<p>According to the <a target="_blank" href="https://docs.python.org/3/tutorial/errors.html#handling-exceptions">Python Documentation</a>:</p>
<blockquote>
<p>Exception handlers don’t just handle exceptions if they occur immediately in the try clause, but also <strong>if they occur inside functions that are called (even indirectly) in the try clause.</strong></p>
</blockquote>
<p>Let's see an example to illustrate this:</p>
<pre><code>def f(i):
    <span class="hljs-keyword">try</span>:
        g(i)
    except IndexError:
        print(<span class="hljs-string">"Please enter a valid index"</span>)

def g(i):
    a = <span class="hljs-string">"Hello"</span>
    <span class="hljs-keyword">return</span> a[i]

f(<span class="hljs-number">50</span>)
</code></pre><p>We have the <code>f</code> function and the <code>g</code> function. <code>f</code> calls <code>g</code> in the try clause. With the argument 50, <code>g</code> will raise an IndexError because the index 50 is not valid for the string a. </p>
<p>But <code>g</code> itself doesn't handle the exception. Notice how there is no try ... except statement in the <code>g</code> function. Since it doesn't handle the exception, it "sends" it to <code>f</code> to see if it can handle it, as you can see in the diagram below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/12/image-16.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Since f <em>does</em> know how to handle an IndexError, the situation is handled gracefully and this is the output:</p>
<pre><code class="lang-python">Please enter a valid index
</code></pre>
<p><strong>💡 Note:</strong> If <code>f</code> had not handled the exception, the program would have ended abruptly with the default error message for an IndexError.</p>
<h3 id="heading-accessing-specific-details-of-exceptions">🔸 Accessing Specific Details of Exceptions</h3>
<p>Exceptions are objects in Python, so you can assign the exception that was raised to a variable. This way, you can print the default description of the exception and access its arguments.</p>
<p>According to the <a target="_blank" href="https://docs.python.org/3/tutorial/errors.html#handling-exceptions">Python Documentation</a>:</p>
<blockquote>
<p>The except clause <strong>may specify a variable after the exception name</strong>. The variable is bound to an exception instance with the arguments stored in instance.args.</p>
</blockquote>
<p>Here we have an example (see below) were we assign the instance of <code>ZeroDivisionError</code> to the variable <code>e</code>. Then, we can use this variable within the except clause to access the type of the exception, its message, and arguments. </p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">divide_integers</span>():</span>
    <span class="hljs-keyword">while</span> <span class="hljs-literal">True</span>:
        <span class="hljs-keyword">try</span>:
            a = int(input(<span class="hljs-string">"Please enter the numerator: "</span>))
            b = int(input(<span class="hljs-string">"Please enter the denominator: "</span>))
            print(a / b)
        <span class="hljs-comment"># Here we assign the exception to the variable e</span>
        <span class="hljs-keyword">except</span> ZeroDivisionError <span class="hljs-keyword">as</span> e:
            print(type(e))
            print(e)
            print(e.args)

divide_integers()
</code></pre>
<p>The corresponding output would be:</p>
<pre><code class="lang-python">Please enter the numerator: <span class="hljs-number">5</span>
Please enter the denominator: <span class="hljs-number">0</span>

<span class="hljs-comment"># Type</span>
&lt;<span class="hljs-class"><span class="hljs-keyword">class</span> '<span class="hljs-title">ZeroDivisionError</span>'&gt;

# <span class="hljs-title">Message</span>
<span class="hljs-title">division</span> <span class="hljs-title">by</span> <span class="hljs-title">zero</span>

# <span class="hljs-title">Args</span>
(<span class="hljs-params"><span class="hljs-string">'division by zero'</span>,</span>)</span>
</code></pre>
<p><strong>💡 Tip:</strong> If you are familiar with special methods, according to the <a target="_blank" href="https://docs.python.org/3/tutorial/errors.html#handling-exceptions">Python Documentation</a>: "for convenience, the exception instance defines <code>[__str__()](https://docs.python.org/3/reference/datamodel.html#object.__str__)</code> so the arguments can be printed directly without having to reference <code>.args</code>."</p>
<h2 id="heading-4-now-lets-add-the-else-clause">4️⃣ Now Let's Add: The "else" Clause</h2>
<p>The <code>else</code> clause is optional, but it's a great tool because it lets us execute code that should only run if no exceptions were raised in the try clause.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/12/image-17.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>According to the <a target="_blank" href="https://docs.python.org/3/tutorial/errors.html#handling-exceptions">Python Documentation</a>:</p>
<blockquote>
<p>The <a target="_blank" href="https://docs.python.org/3/reference/compound_stmts.html#try"><code>try</code></a> … <a target="_blank" href="https://docs.python.org/3/reference/compound_stmts.html#except"><code>except</code></a> statement has an <strong>optional</strong> <em>else clause</em>, which, when present, must follow all except clauses. It is useful for code that must be executed <strong>if the try clause does not raise an exception.</strong></p>
</blockquote>
<p>Here is an example of the use of the <code>else</code> clause:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">divide_integers</span>():</span>
    <span class="hljs-keyword">while</span> <span class="hljs-literal">True</span>:
        <span class="hljs-keyword">try</span>:
            a = int(input(<span class="hljs-string">"Please enter the numerator: "</span>))
            b = int(input(<span class="hljs-string">"Please enter the denominator: "</span>))
            result = a / b
        <span class="hljs-keyword">except</span> (ZeroDivisionError, ValueError):
            print(<span class="hljs-string">"Please enter valid integers. The denominator can't be zero"</span>)
        <span class="hljs-keyword">else</span>:
            print(result)

divide_integers()
</code></pre>
<p>If no exception are raised, the result is printed:</p>
<pre><code class="lang-python">Please enter the numerator: <span class="hljs-number">5</span>
Please enter the denominator: <span class="hljs-number">5</span>
<span class="hljs-number">1.0</span>
</code></pre>
<p>But if an exception is raised, the result is not printed:</p>
<pre><code class="lang-python">Please enter the numerator: <span class="hljs-number">5</span>
Please enter the denominator: <span class="hljs-number">0</span>
Please enter valid integers. The denominator can<span class="hljs-string">'t be zero</span>
</code></pre>
<p>💡 <strong>Tip:</strong> According to the <a target="_blank" href="https://docs.python.org/3/tutorial/errors.html#handling-exceptions">Python Documentation</a>:</p>
<blockquote>
<p>The use of the <code>else</code> clause is better than adding additional code to the <a target="_blank" href="https://docs.python.org/3/reference/compound_stmts.html#try"><code>try</code></a> clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the <code>try</code> … <code>except</code> statement.</p>
</blockquote>
<h2 id="heading-5-the-finally-clause">5️⃣ The "finally" Clause</h2>
<p>The finally clause is the last clause in this sequence. It is <strong>optional</strong>, but if you include it, it has to be the last clause in the sequence. The <code>finally</code> clause is <strong>always</strong> executed, even if an exception was raised in the try clause.  </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/12/image-19.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>According to the <a target="_blank" href="https://docs.python.org/3/tutorial/errors.html#defining-clean-up-actions">Python Documentation</a>:</p>
<blockquote>
<p>If a <a target="_blank" href="https://docs.python.org/3/reference/compound_stmts.html#finally"><code>finally</code></a> clause is present, the <a target="_blank" href="https://docs.python.org/3/reference/compound_stmts.html#finally"><code>finally</code></a> clause will execute as the last task before the <a target="_blank" href="https://docs.python.org/3/reference/compound_stmts.html#try"><code>try</code></a> statement completes. The <a target="_blank" href="https://docs.python.org/3/reference/compound_stmts.html#finally"><code>finally</code></a> clause <strong>runs whether or not the <a target="_blank" href="https://docs.python.org/3/reference/compound_stmts.html#try"><code>try</code></a> statement produces an exception.</strong></p>
</blockquote>
<p>The finally clause is usually used to perform "clean-up" actions that should always be completed. For example, if we are working with a file in the try clause, we will always need to close the file, even if an exception was raised when we were working with the data.</p>
<p>Here is an example of the finally clause:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">divide_integers</span>():</span>
    <span class="hljs-keyword">while</span> <span class="hljs-literal">True</span>:
        <span class="hljs-keyword">try</span>:
            a = int(input(<span class="hljs-string">"Please enter the numerator: "</span>))
            b = int(input(<span class="hljs-string">"Please enter the denominator: "</span>))
            result = a / b
        <span class="hljs-keyword">except</span> (ZeroDivisionError, ValueError):
            print(<span class="hljs-string">"Please enter valid integers. The denominator can't be zero"</span>)
        <span class="hljs-keyword">else</span>:
            print(result)
        <span class="hljs-keyword">finally</span>:
            print(<span class="hljs-string">"Inside the finally clause"</span>)

divide_integers()
</code></pre>
<p>This is the output when no exceptions were raised:</p>
<pre><code>Please enter the numerator: <span class="hljs-number">5</span>
Please enter the denominator: <span class="hljs-number">5</span>
<span class="hljs-number">1.0</span>
Inside the <span class="hljs-keyword">finally</span> clause
</code></pre><p>This is the output when an exception was raised:</p>
<pre><code class="lang-python">Please enter the numerator: <span class="hljs-number">5</span>
Please enter the denominator: <span class="hljs-number">0</span>
Please enter valid integers. The denominator can<span class="hljs-string">'t be zero
Inside the finally clause</span>
</code></pre>
<p>Notice how the <code>finally</code> clause <strong>always</strong> runs.</p>
<p><strong>❗️Important:</strong> remember that the <code>else</code> clause and the <code>finally</code> clause are optional, but if you decide to include both, the finally clause has to be the last clause in the sequence.</p>
<h2 id="heading-6-raising-exceptions">6️⃣ Raising Exceptions</h2>
<p>Now that you know how to handle exceptions in Python, I would like to share with you this helpful tip: <strong>you can also choose when to raise exceptions in your code.</strong> </p>
<p>This can be helpful for certain scenarios. Let's see how you can do this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/12/image-20.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This line will raise a ValueError with a custom message.</p>
<p>Here we have an example (see below) of a function that prints the value of the items of a list or tuple, or the characters in a string. But you decided that you want the list, tuple, or string to be of length 5. You start the function with an if statement that checks if the length of the argument <code>data</code> is 5. If it isn't, a ValueError exception is raised:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">print_five_items</span>(<span class="hljs-params">data</span>):</span>

    <span class="hljs-keyword">if</span> len(data) != <span class="hljs-number">5</span>:
        <span class="hljs-keyword">raise</span> ValueError(<span class="hljs-string">"The argument must have five elements"</span>)

    <span class="hljs-keyword">for</span> item <span class="hljs-keyword">in</span> data:
        print(item)

print_five_items([<span class="hljs-number">5</span>, <span class="hljs-number">2</span>])
</code></pre>
<p>The output would be:</p>
<pre><code class="lang-python">Traceback (most recent call last):
  File <span class="hljs-string">"&lt;path&gt;"</span>, line <span class="hljs-number">122</span>, <span class="hljs-keyword">in</span> &lt;module&gt;
    print_five_items([<span class="hljs-number">5</span>, <span class="hljs-number">2</span>])
  File <span class="hljs-string">"&lt;path&gt;"</span>, line <span class="hljs-number">117</span>, <span class="hljs-keyword">in</span> print_five_items
    <span class="hljs-keyword">raise</span> ValueError(<span class="hljs-string">"The argument must have five elements"</span>)
ValueError: The argument must have five elements
</code></pre>
<p>Notice how the last line displays the descriptive message:</p>
<pre><code class="lang-python">ValueError: The argument must have five elements
</code></pre>
<p>You can then choose how to handle the exception with a try ... except statement. You could add an else clause and/or a finally clause. You can customize it to fit your needs. </p>
<h3 id="heading-helpful-resources">🔹 Helpful Resources</h3>
<ul>
<li><a target="_blank" href="https://docs.python.org/3/tutorial/errors.html#exceptions">Exceptions</a></li>
<li><a target="_blank" href="https://docs.python.org/3/tutorial/errors.html#handling-exceptions">Handling Exceptions</a></li>
<li><a target="_blank" href="https://docs.python.org/3/tutorial/errors.html#defining-clean-up-actions">Defining Clean-up Actions</a></li>
</ul>
<p><strong>I hope you enjoyed reading my article and found it helpful.</strong> Now you have the necessary tools to handle exceptions in Python and you can use them to your advantage when you write Python code. ? <a target="_blank" href="https://www.udemy.com/user/estefania-cn/">Check out my online courses</a>. You can follow me on <a target="_blank" href="https://twitter.com/EstefaniaCassN">Twitter</a>. </p>
<p>⭐️ You may enjoy my other freeCodeCamp /news articles:</p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/python-property-decorator/">The @property Decorator in Python: Its Use Cases, Advantages, and Syntax</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/data-structures-101-graphs-a-visual-introduction-for-beginners-6d88f36ec768/">Data Structures 101: Graphs — A Visual Introduction for Beginners</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/data-structures-101-arrays-a-visual-introduction-for-beginners-7f013bcc355a/">Data Structures 101: Arrays — A Visual Introduction for Beginners</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
