<?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[ error 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[ error handling - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Thu, 14 May 2026 04:33:06 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/error-handling/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ The JavaScript Error Handling Handbook ]]>
                </title>
                <description>
                    <![CDATA[ Errors and exceptions are inevitable in application development. As programmers, it is our responsibility to handle these errors gracefully so that the user experience of the application is not compromised. Handling errors correctly also helps progra... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-javascript-error-handling-handbook/</link>
                <guid isPermaLink="false">68715d56bc2af40281bdf584</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ error handling ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Tapas Adhikary ]]>
                </dc:creator>
                <pubDate>Fri, 11 Jul 2025 18:52:06 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1752254732491/dd413499-64f4-4a20-8fd6-7f73cfcd55c0.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Errors and exceptions are inevitable in application development. As programmers, it is our responsibility to handle these errors gracefully so that the user experience of the application is not compromised. Handling errors correctly also helps programmers debug and understand what caused them so they can deal with them.</p>
<p>JavaScript has been a popular programming language for over three decades. We build web, mobile, PWA, and server-side applications using JavaScript and various popular JavaScript-based libraries (like ReactJS) and frameworks (like Next.js, Remix, and so on).</p>
<p>Being a loosely typed language, JavaScript imposes the challenge of handling type safety correctly. TypeScript is useful for managing types, but we still need to handle runtime errors efficiently in our code.</p>
<p>Errors like <code>TypeError</code>, <code>RangeError</code>, <code>ReferenceError</code> are probably pretty familiar to you if you’ve been building with JavaScript for a while. All these errors may cause invalid data, bad page transitions, unwanted results, or even the entire application to crash – none of which will make end users happy!</p>
<p>In this handbook, you’ll learn everything you need to know about error handling in JavaScript. We will start with an understanding of errors, their types, and occurrences. Then you’ll learn how to deal with these errors so that they don’t cause a bad user experience. At the end, you’ll also learn to build your own custom error types and clean-up methodologies to handle your code flow better for optimizations and performance.</p>
<p>I hope you enjoy reading along and practising the tasks I have provided at the end of the article.</p>
<p>This handbook is also available as a video session as part of the <a target="_blank" href="https://www.youtube.com/watch?v=t8QXF85YovE&amp;list=PLIJrr73KDmRw2Fwwjt6cPC_tk5vcSICCu">40 Days of JavaScript</a> initiative. Please check it out.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/XpMW-gxNYD8" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-errors-in-javascript">Errors in JavaScript</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-handling-errors-with-the-try-and-catch">Handling Errors With the try and catch</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-the-try-block">The try Block</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-catch-block">The catch Block</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-error-handling-real-world-use-cases">Error Handling: Real-World Use Cases</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-handling-division-by-zero">Handling Division by Zero</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-handling-json">Handling JSON</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-anatomy-of-the-error-object">Anatomy of the Error Object</a></p>
<ul>
<li><a class="post-section-overview" href="#heading-what-is-the-error-object">What is the Error Object?</a></li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-throwing-errors-and-re-throwing-errors">Throwing Errors and Re-throwing Errors</a></p>
<ul>
<li><a class="post-section-overview" href="#heading-rethrowing">Rethrowing</a></li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-the-finally-with-try-catch">The finally with try-catch</a></p>
<ul>
<li><a class="post-section-overview" href="#heading-caution-with-finally">Caution with finally</a></li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-custom-errors">Custom Errors</a></p>
<ul>
<li><a class="post-section-overview" href="#heading-a-real-world-use-case-of-custom-errors">A Real-World Use Case of Custom Errors</a></li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-task-assignments-for-you">Task Assignments for You</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-find-the-output">Find the Output</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-payment-process-validation">Payment Process Validation</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-40-days-of-javascript-challenge-initiative">40 Days of JavaScript Challenge Initiative</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-before-we-end">Before We End...</a></p>
</li>
</ol>
<h2 id="heading-errors-in-javascript">Errors in JavaScript</h2>
<p>Errors and exceptions are the events that disrupt program execution. JavaScript parses and executes code line by line. The source code gets evaluated with the grammar of the programming language to ensure it is valid and executable. If there is a mismatch, JavaScript encounters a <code>parsing error</code>. You’ll need to make sure you follow the right syntax and grammar of the language to stay away from parsing errors.</p>
<p>Take a look at the code snippet below. Here, we have made the mistake of not closing the parentheses for the console.log.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">"hi"</span>
</code></pre>
<p>This will lead to a Syntax Error like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1743047661114/11a445de-132f-49d0-9f3c-8516a0d21950.png" alt="Uncaught SyntaxError" class="image--center mx-auto" width="656" height="44" loading="lazy"></p>
<p>Other types of errors can happen due to wrong data input, trying to read a value or property that doesn’t exist, or acting on inaccurate data. Let’s see some examples:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(x); <span class="hljs-comment">// Uncaught ReferenceError: x is not defined</span>

<span class="hljs-keyword">let</span> obj = <span class="hljs-literal">null</span>;
<span class="hljs-built_in">console</span>.log(obj.name); <span class="hljs-comment">// Uncaught TypeError: Cannot read properties of null</span>

<span class="hljs-keyword">let</span> arr = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Array</span>(<span class="hljs-number">-1</span>) <span class="hljs-comment">// Uncaught RangeError: Invalid array length</span>

<span class="hljs-built_in">decodeURIComponent</span>(<span class="hljs-string">"%"</span>); <span class="hljs-comment">// Uncaught URIError: URI malformed</span>

<span class="hljs-built_in">eval</span>(<span class="hljs-string">"var x = ;"</span>); <span class="hljs-comment">// Uncaught EvalError</span>
</code></pre>
<p>Here is the list of possible runtime errors you may encounter, along with their descriptions:</p>
<ul>
<li><p><code>ReferenceError</code> – Occurs when trying to access a variable that is not defined.</p>
</li>
<li><p><code>TypeError</code> – Occurs when an operation is performed on a value of the wrong type.</p>
</li>
<li><p><code>RangeError</code> – Occurs when a value is outside the allowable range.</p>
</li>
<li><p><code>SyntaxError</code> – Occurs when there is a mistake in the syntax of the JavaScript code.</p>
</li>
<li><p><code>URIError</code> – Occurs when an incorrect URI function is used in encoding and decoding URIs.</p>
</li>
<li><p><code>EvalError</code> – Occurs when there is an issue with the eval() function.</p>
</li>
<li><p><code>InternalError</code> – Occurs when the JavaScript engine runs into an internal limit (stack overflow).</p>
</li>
<li><p><code>AggregateError</code> – Introduced in ES2021, used for handling multiple errors at once.</p>
</li>
<li><p><code>Custom Errors</code> – These are user-defined errors, and we will learn how to create and use them soon.</p>
</li>
</ul>
<p>Have you noticed that all the code examples we used above result in a message explaining what the error is about? If you look at those messages closely, you will find a word called <code>Uncaught</code>. It means the error occurred, but it was not caught and managed. That’s exactly what we will now go for – so you know how to handle these errors.</p>
<h2 id="heading-handling-errors-with-the-try-and-catch">Handling Errors With the <code>try</code> and <code>catch</code></h2>
<p>JavaScript applications can break for various reasons, like invalid syntax, invalid data, missing API responses, user mistakes, and so on. Most of these reasons may lead to an application crash, and your users will see a blank white page.</p>
<p>Rather than letting the application crash, you can gracefully handle these situations using <code>try…catch</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">try</span> {
    <span class="hljs-comment">// logic or code</span>
} <span class="hljs-keyword">catch</span> (err) {
    <span class="hljs-comment">// handle error</span>
}
</code></pre>
<h3 id="heading-the-try-block">The <code>try</code> Block</h3>
<p>The <code>try</code> block contains the code – the business logic – which might throw an error. Developers always want their code to be error-free. But at the same time, you should be aware that the code might throw an error for several possible reasons, like:</p>
<ul>
<li><p>Parsing JSON</p>
</li>
<li><p>Running API logic</p>
</li>
<li><p>Accessing nested object properties</p>
</li>
<li><p>DOM manipulations</p>
</li>
<li><p>… and many more</p>
</li>
</ul>
<p>When the code inside the try block throws an error, the code execution of the remaining code in the try block will be suspended, and the control moves to the nearest catch block. If no error occurs, the catch block is skipped completely.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">try</span> {
  <span class="hljs-comment">// Code that might throw an error</span>
} <span class="hljs-keyword">catch</span> (error) {
  <span class="hljs-comment">// Handle the error here</span>
}
</code></pre>
<h3 id="heading-the-catch-block">The <code>catch</code> Block</h3>
<p>The catch block runs only if an error was thrown in the try block. It receives the <code>Error object</code> as a parameter to give us more information about the error. In the example shown below, we are using something called <code>abc</code> without declaring it. JavaScript will throw an error like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">try</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"execution starts here"</span>);
    abc;
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"execution ends here"</span>);
} <span class="hljs-keyword">catch</span> (err) {
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"An Error has occured"</span>, err);
}
</code></pre>
<p>JavaScript executes code line by line. The execution sequence of the above code will be:</p>
<ul>
<li><p>First, the string "execution starts here" will be logged to the console.</p>
</li>
<li><p>Then the control will move to the next line and find the <code>abc</code> there. What is it? JavaScript doesn’t find any definition of it anywhere. It’s time to raise the alarm and throw an error. The control doesn’t move to the next line (the next console log), but rather moves to the catch block.</p>
</li>
<li><p>In the catch block, we handle the error by logging it to the console. We could do many other things like show a toast message, send the user an email, or switch off a toaster (why not if your customer needs it).</p>
</li>
</ul>
<p>Without try...catch, the error would crash the app.</p>
<h2 id="heading-error-handling-real-world-use-cases">Error Handling: Real-World Use Cases</h2>
<p>Let’s now see some of the real-world use cases of error handling with try…catch.</p>
<h3 id="heading-handling-division-by-zero">Handling Division by Zero</h3>
<p>Here is a function that divides a number by another number. So, we have parameters passed to the function for both numbers. We want to make sure that the division never encounters an error for dividing a number by zero (0).</p>
<p>As a proactive measure, we have written a condition that if the divisor is zero, we will throw an error saying that division by zero is not allowed. In every other case, we will proceed with the division operation. In case of an error, the catch block will handle the error and do what’s needed (in this case, logging the error to the console).</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">divideNumbers</span>(<span class="hljs-params">a, b</span>) </span>{
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">if</span> (b === <span class="hljs-number">0</span>) {
            <span class="hljs-keyword">const</span> err = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Division by zero is not allowed."</span>);
            <span class="hljs-keyword">throw</span> err;
        }
        <span class="hljs-keyword">const</span> result = a/b;
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The result is <span class="hljs-subst">${result}</span>`</span>);
    } <span class="hljs-keyword">catch</span>(error) {
        <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Got a Math Error:"</span>, error.message)
    }
}
</code></pre>
<p>Now, if we invoke the function with the following arguments, we will get a result of 5, and the second argument is a non-zero value.</p>
<pre><code class="lang-javascript">divideNumbers(<span class="hljs-number">15</span>, <span class="hljs-number">3</span>); <span class="hljs-comment">// The result is 5</span>
</code></pre>
<p>But if we pass the 0 value for the second argument, the program will throw an error, and it will be logged into the console.</p>
<pre><code class="lang-javascript">divideNumbers(<span class="hljs-number">15</span>, <span class="hljs-number">0</span>);
</code></pre>
<p>Output:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1752115297863/02d9e89d-e5c1-4759-a11e-ab57d04bcfff.png" alt="Math Error" class="image--center mx-auto" width="927" height="130" loading="lazy"></p>
<h3 id="heading-handling-json">Handling JSON</h3>
<p>Often, you will get JSON as a response to an API call. You need to parse this JSON in your JavaScript code to extract the values. What if the API sends you some malformed JSON by mistake? You can’t afford to let your user interface crash because of this. You need to handle it gracefully – and here comes the try…catch block again to the rescue:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">parseJSONSafely</span>(<span class="hljs-params">str</span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">JSON</span>.parse(str);
  } <span class="hljs-keyword">catch</span> (err) {
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Invalid JSON:"</span>, err.message);
    <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
  }
}

<span class="hljs-keyword">const</span> userData = parseJSONSafely(<span class="hljs-string">'{"name": "tapaScript"}'</span>); <span class="hljs-comment">// Parsed</span>
<span class="hljs-keyword">const</span> badData = parseJSONSafely(<span class="hljs-string">'name: tapaScript'</span>);         <span class="hljs-comment">// Handled gracefully</span>
</code></pre>
<p>Without try...catch, the second call will crash the app.</p>
<h2 id="heading-anatomy-of-the-error-object">Anatomy of the Error Object</h2>
<p>Getting errors in programming can be a scary feeling. But <code>Error</code>s in JavaScript aren’t just some scary, annoying messages – they are structured objects that carry a lot of helpful information about what went wrong, where, and why.</p>
<p>As developers, we need to understand the anatomy of the <code>Error</code> object to help us better with faster debugging and smarter recovery in production-level application issues.</p>
<p>Let’s deep dive into the Error object, its properties, and how to use it effectively with examples.</p>
<h3 id="heading-what-is-the-error-object">What is the Error Object?</h3>
<p>The JavaScript engine throws an <code>Error</code> object when something goes wrong during runtime. This object contains helpful information like:</p>
<ul>
<li><p>An error message: This is a human-readable error message.</p>
</li>
<li><p>The error type: TypeError, ReferenceError, SyntaxError, and so on that we discussed above.</p>
</li>
<li><p>The stack trace: This helps you navigate to the root of the error. It is a string containing the stack trace at the point the error was thrown.</p>
</li>
</ul>
<p>Let’s take a look at the code snippet below. The JavaScript engine will throw an error in this code, as the variable <code>y</code> is not defined. The error object contains the error name (type), message, and the stack trace information.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">doSomething</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> x = y + <span class="hljs-number">1</span>; <span class="hljs-comment">// y is not defined</span>
}
<span class="hljs-keyword">try</span> {
  doSomething();
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-built_in">console</span>.log(err.name);    <span class="hljs-comment">// ReferenceError</span>
  <span class="hljs-built_in">console</span>.log(err.message); <span class="hljs-comment">// y is not defined</span>
  <span class="hljs-built_in">console</span>.log(err.stack); <span class="hljs-comment">// ReferenceError: y is not defined</span>
                          <span class="hljs-comment">// at doSomething (&lt;anonymous&gt;:2:13)</span>
                          <span class="hljs-comment">// at &lt;anonymous&gt;:5:3</span>
}
</code></pre>
<p>Tip: If you need any specific properties from the error object, you can use destructuring to do that. Here is an example where we are only interested in the error name and message, not the stack.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">try</span> {
  <span class="hljs-built_in">JSON</span>.parse(<span class="hljs-string">"{ invalid json }"</span>);
} <span class="hljs-keyword">catch</span> ({name, message}) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Name:"</span>, name);       <span class="hljs-comment">// Name: SyntaxError</span>
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Message:"</span>, message); <span class="hljs-comment">// Message: Expected property name or '}' in JSON at position 2 (line 1 column 3)</span>
}
</code></pre>
<h2 id="heading-throwing-errors-and-re-throwing-errors">Throwing Errors and Re-throwing Errors</h2>
<p>JavaScript provides a <code>throw</code> statement to trigger an error manually. It is very helpful when you want to handle an invalid condition in your code (remember the divide by zero problem?).</p>
<p>To throw an error, you need to create an instance of the <code>Error</code> object with details and then throw it.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Something is bad!"</span>);
</code></pre>
<p>When the code execution encounters a <code>throw</code> statement,</p>
<ul>
<li><p>It stops the execution of the current code block immediately.</p>
</li>
<li><p>The control moves to the nearest catch block (if any).</p>
</li>
<li><p>If the catch block is not found, the error will not be caught. The error gets bubbled up, and may end up crashing the program. You can learn more in-depth about events and event bubbling from <a target="_blank" href="https://www.youtube.com/watch?v=ybgI5vVE668">here</a>.</p>
</li>
</ul>
<h3 id="heading-rethrowing">Rethrowing</h3>
<p>At times, catching the error itself in the catch block is not enough. Sometimes, you may not know how to handle the error completely, and you might want to do additional things, like:</p>
<ul>
<li><p>Adding more context to the error.</p>
</li>
<li><p>Logging the error into a file-based logger.</p>
</li>
<li><p>Passing the error to someone more specialized to handle it.</p>
</li>
</ul>
<p>This is where <code>rethrow</code> comes in. With rethrowing, you catch an error, do something else with it, and then throw it again.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">processData</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">try</span> {
    parseUserData();
  } <span class="hljs-keyword">catch</span> (err) {
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Error in processData:"</span>, err.message);
    <span class="hljs-keyword">throw</span> err; <span class="hljs-comment">// Rethrow so the outer function can handle it too</span>
  }
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">main</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">try</span> {
    processData();
  } <span class="hljs-keyword">catch</span> (err) {
    handleErrorBetter(err);
  }
}
</code></pre>
<p>In the code above, the <code>processData()</code> function catches an error, logs it, and then <code>throw</code>s it again. The outer <code>main()</code> function can now catch it and do something more to handle it better.</p>
<p>In the real-world application development, you would want to separate the concerns for errors, like:</p>
<ul>
<li><p><strong>API Layer</strong> – In this layer, you can detect HTTP failures</p>
<pre><code class="lang-javascript">  <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchUser</span>(<span class="hljs-params">id</span>) </span>{
    <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">`/users/<span class="hljs-subst">${id}</span>`</span>);
    <span class="hljs-keyword">if</span> (!res.ok) <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"User not found"</span>); <span class="hljs-comment">// throw it here</span>
    <span class="hljs-keyword">return</span> res.json();
  }
</code></pre>
</li>
<li><p><strong>Service Layer</strong> – In this layer, you handle business logic. So the error will be handled for invalid conditions.</p>
<pre><code class="lang-javascript">  <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getUser</span>(<span class="hljs-params">id</span>) </span>{
    <span class="hljs-keyword">try</span> {
      <span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> fetchUser(id);
      <span class="hljs-keyword">return</span> user;
    } <span class="hljs-keyword">catch</span> (err) {
      <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Fetching user failed:"</span>, err.message);
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Unable to load user profile"</span>); <span class="hljs-comment">// rethrowing </span>
    }
  }
</code></pre>
</li>
<li><p><strong>UI Layer</strong> – Show a user-friendly error message.</p>
<pre><code class="lang-javascript">  <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">showUserProfile</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">try</span> {
      <span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> getUser(<span class="hljs-number">123</span>);
      renderUser(user);
    } <span class="hljs-keyword">catch</span> (err) {
      displayError(err.message); <span class="hljs-comment">// A proper message show to the user</span>
    }
  }
</code></pre>
</li>
</ul>
<h2 id="heading-the-finally-with-try-catch">The <code>finally</code> with try-catch</h2>
<p>The try…catch block gives us a way to handle errors gracefully. But you may always want to execute some code irrespective of whether an error occurred or not. For example, closing the database connection, stopping a loader, resetting some states, and so on. That’s where <code>finally</code> comes in.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">try</span> {
  <span class="hljs-comment">// Code might throw an error</span>
} <span class="hljs-keyword">catch</span> (error) {
  <span class="hljs-comment">// Handle the error</span>
} <span class="hljs-keyword">finally</span> {
  <span class="hljs-comment">// Always runs, whether an error occured or not</span>
}
</code></pre>
<p>Let’s take an example:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">performTask</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Doing something cool..."</span>);
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Oops!"</span>);
  } <span class="hljs-keyword">catch</span> (err) {
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Caught error:"</span>, err.message);
  } <span class="hljs-keyword">finally</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Cleanup: Task finished (success or fail)."</span>);
  }
}

performTask();
</code></pre>
<p>In the <code>performTask()</code> function, the error is thrown after the first console log. So, the control will move to the catch block and log the error. After that, the <code>finally</code> block will execute its console log.</p>
<p>Output:</p>
<pre><code class="lang-bash">Doing something cool...
Caught error: Oops!
Cleanup: Task finished (success or fail).
</code></pre>
<p>Let’s take a more real-world use case of making an API call and handling the loading spinner:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">loadUserData</span>(<span class="hljs-params"></span>) </span>{
  showSpinner(); <span class="hljs-comment">// Show the spinner here</span>

  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'/api/user'</span>);
    <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> res.json();
    displayUser(data);
  } <span class="hljs-keyword">catch</span> (err) {
    showError(<span class="hljs-string">"Failed to load user."</span>);
  } <span class="hljs-keyword">finally</span> {
    hideSpinner(); <span class="hljs-comment">// Hide spinner for both success and fail cases.</span>
  }
}
</code></pre>
<p>Usually, we show a loading spinner while making an API (asynchronous) call from the browser. Irrespective of the successful response or an error from the API call, we must stop showing the loading spinner. Instead of executing the code logic twice to stop the spinner (once inside the <code>try</code> block and then again inside the <code>catch</code> block), you can do it inside the <code>finally</code> block.</p>
<h3 id="heading-caution-with-finally">Caution with <code>finally</code></h3>
<p>The <code>finally</code> block can override return values or a thrown error. This behaviour may be confusing and can lead to bugs as well.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">test</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-string">'from try'</span>;
  } <span class="hljs-keyword">finally</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-string">'from finally'</span>;
  }
}

<span class="hljs-built_in">console</span>.log(test());
</code></pre>
<p>What do you think the above code returns?</p>
<p>It will return <code>'from finally'</code>. The return <code>'from try'</code> is completely ignored. The return from finally overrides it silently.</p>
<p>Let’s see one more example of the same problem:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">willThrow</span>(<span class="hljs-params"></span>) </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">"Original Error"</span>);
  } <span class="hljs-keyword">finally</span> {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Overriding Error"</span>); <span class="hljs-comment">// The original error is lost</span>
  }
}

<span class="hljs-keyword">try</span> {
  willThrow();
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-built_in">console</span>.log(err.message); <span class="hljs-comment">// "Overriding Error"</span>
}
</code></pre>
<p>Here, the original error (<code>"Original Error”</code>) is swallowed. The finally block overrides the actual root cause.</p>
<p>When using <code>finally</code>:</p>
<ul>
<li><p>Avoid returns and throws from <code>finally</code> as much as possible.</p>
</li>
<li><p>Avoid performing logic in the <code>finally</code> block that may impact the actual outcome. The <code>try</code> block is the best place for that.</p>
</li>
<li><p>Any critical decision-making must be avoided inside the <code>finally</code> block</p>
</li>
<li><p>Use <code>finally</code> for cleanup activities, such as closing files, connections, and stopping loading spinners, etc.</p>
</li>
<li><p>Ensure the <code>finally</code> block contains side-effect-free code.</p>
</li>
</ul>
<h2 id="heading-custom-errors">Custom Errors</h2>
<p>Using the generic Error and its existing types, like ReferenceError, SyntaxError, and so on, can be a bit vague in complex applications. JavaScript lets you create custom errors that are more related to your business use cases. The custom errors can provide:</p>
<ul>
<li><p>Additional contextual information about the error.</p>
</li>
<li><p>Clarity about the error</p>
</li>
<li><p>More readable logs</p>
</li>
<li><p>The ability to handle multiple error cases conditionally.</p>
</li>
</ul>
<p>A custom error in JavaScript is a user-defined error type that extends the built-in Error class. The custom error should be an <a target="_blank" href="https://www.youtube.com/watch?v=kG5t34ciG9w">ES6 Class</a> that extends JavaScript’s Error class. We can use the <code>super()</code> in the constructor function to inherit the message property of the Error class. You can optionally assign a name and clean the stack trace for the custom error.</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyCustomError</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Error</span> </span>{
  <span class="hljs-keyword">constructor</span>(message) {
    <span class="hljs-built_in">super</span>(message);         <span class="hljs-comment">// Inherit message property</span>
    <span class="hljs-built_in">this</span>.name = <span class="hljs-built_in">this</span>.constructor.name; <span class="hljs-comment">// Optional but recommended</span>
    <span class="hljs-built_in">Error</span>.captureStackTrace(<span class="hljs-built_in">this</span>, <span class="hljs-built_in">this</span>.constructor); <span class="hljs-comment">// Clean stack trace</span>
  }
}
</code></pre>
<p>Let’s now see a real-world use case for a custom error.</p>
<h3 id="heading-a-real-world-use-case-of-custom-errors">A Real-World Use Case of Custom Errors</h3>
<p>Using a form on a web page is an extremely common use case. A form may contain one or more input fields. It is recommended to validate the user inputs before we process the form data for any server actions.</p>
<p>Let’s create a custom validation error we can leverage for validating multiple form input data, like the user’s email, age, phone number, and more.</p>
<p>First, we’ll create a class called <code>ValidationError</code> that extends the <code>Error</code> class. The constructor function sets up the <code>ValidationError</code> class with an error message. We can also instantiate additional properties, like name, field, and so on.</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ValidationError</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Error</span> </span>{
  <span class="hljs-keyword">constructor</span>(field, message) {
    <span class="hljs-built_in">super</span>(<span class="hljs-string">`<span class="hljs-subst">${field}</span>: <span class="hljs-subst">${message}</span>`</span>);
    <span class="hljs-built_in">this</span>.name = <span class="hljs-string">"ValidationError"</span>;
    <span class="hljs-built_in">this</span>.field = field;
  }
}
</code></pre>
<p>Now, let's see how to use <code>ValidationError</code>. We can validate a user model to check its properties and throw a <code>ValidationError</code> whenever the expectations mismatch.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">validateUser</span>(<span class="hljs-params">user</span>) </span>{
  <span class="hljs-keyword">if</span> (!user.email.includes(<span class="hljs-string">"@"</span>)) {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> ValidationError(<span class="hljs-string">"email"</span>, <span class="hljs-string">"Invalid email format"</span>);
  }
  <span class="hljs-keyword">if</span> (!user.age || user.age &lt; <span class="hljs-number">18</span>) {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> ValidationError(<span class="hljs-string">"age"</span>, <span class="hljs-string">"User must be 18+"</span>);
  }
}
</code></pre>
<p>In the code snippet above,</p>
<ul>
<li><p>We throw an invalid email format validation error if the user’s email doesn’t include the <code>@</code> symbol.</p>
</li>
<li><p>We throw another validation error if the age information of the user is missing or is below 18.</p>
</li>
</ul>
<p>A custom error gives us the power to create domain/usage-specific error types to keep the code more manageable and less error-prone.</p>
<h2 id="heading-task-assignments-for-you">Task Assignments for You</h2>
<p>If you have read the handbook this far, I hope you now have a solid understanding of JavaScript Error Handling. Let’s try out some assignments based on what we have learned so far. It’s going to be fun.</p>
<h3 id="heading-find-the-output">Find the Output</h3>
<p>What will be the output of the following code snippet and why?</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">let</span> r = p + <span class="hljs-number">50</span>;
    <span class="hljs-built_in">console</span>.log(r);
} <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"An error occurred:"</span>, error.name);
}
</code></pre>
<p>Options are:</p>
<ul>
<li><p>ReferenceError</p>
</li>
<li><p>SyntaxError</p>
</li>
<li><p>TypeError</p>
</li>
<li><p>No error, it prints 10</p>
</li>
</ul>
<h3 id="heading-payment-process-validation">Payment Process Validation</h3>
<p>Write a function <code>processPayment(amount)</code> that verifies if the amount is positive and does not exceed the balance. If any condition fails, throw appropriate errors.</p>
<p>Hint: You can think of creating a Custom Error here.</p>
<h2 id="heading-40-days-of-javascript-challenge-initiative">40 Days of JavaScript Challenge Initiative</h2>
<p>There are 101 ways of learning something. But nothing can beat structured and progressive learning methodologies. After spending more than two decades in Software Engineering, I’ve been able to gather the best of JavaScript together to create the <a target="_blank" href="https://www.youtube.com/playlist?list=PLIJrr73KDmRw2Fwwjt6cPC_tk5vcSICCu">40 Days of JavaScript</a> challenge initiative.</p>
<p>Check it out if you want to learn JavaScript with fundamental concepts, projects, and assignments for free (forever). Focusing on the fundamentals of JavaScript will prepare you well for a future in web development.</p>
<h2 id="heading-before-we-end"><strong>Before We End...</strong></h2>
<p>That’s all! I hope you found this article insightful.</p>
<p>Let’s connect:</p>
<ul>
<li><p>Subscribe to my <a target="_blank" href="https://www.youtube.com/tapasadhikary?sub_confirmation=1">YouTube Channel</a>.</p>
</li>
<li><p>Follow on <a target="_blank" href="https://www.linkedin.com/in/tapasadhikary/">LinkedIn</a> if you don't want to miss the daily dose of up-skilling tips.</p>
</li>
<li><p>Check out and follow my open-source work on <a target="_blank" href="https://github.com/atapas">GitHub</a>.</p>
</li>
</ul>
<p>See you soon with my next article. Until then, please take care of yourself and keep learning.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What Are Logs in Programming? ]]>
                </title>
                <description>
                    <![CDATA[ Have you ever run a program, and it crashed? No error messages, no hints, just silence. How do you figure out what went wrong? That's where logging saves the day. Logs keep track of what’s happening inside your code so that when things go wrong, you ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-are-logs-in-programming/</link>
                <guid isPermaLink="false">67abe1c4e2819029e77c7459</guid>
                
                    <category>
                        <![CDATA[ logging ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ error handling ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Syeda Maham Fahim ]]>
                </dc:creator>
                <pubDate>Tue, 11 Feb 2025 23:48:20 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1738685115991/600c01b6-b031-4ce9-a77a-5d88fcdaa68a.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Have you ever run a program, and it crashed? No error messages, no hints, just silence. How do you figure out what went wrong? That's where logging saves the day.</p>
<p>Logs keep track of what’s happening inside your code so that when things go wrong, you don’t have to guess. They’re similar to <code>print</code> or <code>console.log</code>, but more powerful.</p>
<p>In this tutorial, I will use Python to create and walk you through some logging code examples.</p>
<p>Before we talk about logs, let’s understand the different error types you might use or encounter.</p>
<h2 id="heading-types-of-errors">Types of Errors</h2>
<p>When you’re building a production-level application, you need to display errors based on their severity. There are several error types, and the most important ones are:</p>
<ul>
<li><p><strong>DEBUG:</strong> Detailed information, typically useful for diagnosing problems.</p>
</li>
<li><p><strong>INFO:</strong> General information about the program’s progress.</p>
</li>
<li><p><strong>WARNING:</strong> Something unexpected happened, but it’s not critical.</p>
</li>
<li><p><strong>ERROR:</strong> An error occurred, but the program can still run.</p>
</li>
<li><p><strong>CRITICAL:</strong> A very serious error that may stop the program from running.</p>
</li>
</ul>
<h2 id="heading-what-is-logging">What is Logging?</h2>
<p>Now, let’s get straight to the point and understand what logging is.</p>
<p>In simple terms, logs or logging is the act of recording information about everything your program does. The recorded information could be anything, from basic details like which functions were called to more detailed ones like tracking errors or performance issues.</p>
<h3 id="heading-why-do-we-need-logging">Why Do We Need Logging?</h3>
<p>You might be thinking, "If logs are printing errors, info, and so on, I can just use print statements. Why do I need logging?" Well, <code>print</code> works, but logging gives you more control:</p>
<p>↳ It can store messages in a file.<br>↳ It has different levels (info, warning, error, and so on).<br>↳ You can filter messages based on importance.<br>↳ It helps in debugging without cluttering your code.</p>
<p>These are things <code>print</code> statements can't do effectively.</p>
<h2 id="heading-how-to-add-logs-in-python">How to Add Logs in Python</h2>
<p>In Python, the <code>logging</code> module is built specifically for logging purposes.</p>
<p>Let’s set up some logs to see how they work.</p>
<h3 id="heading-step-1-import-the-logging-module">Step 1: Import the Logging Module</h3>
<p>To start using logging, we need to import the module:</p>
<pre><code class="lang-bash">import logging
</code></pre>
<h3 id="heading-step-2-log-messages">Step 2: Log Messages</h3>
<p>Now, you can start logging messages in your program. You can use different log levels based on the importance of the message. As a reminder, those levels are (from least to most urgent):</p>
<ul>
<li><p>DEBUG</p>
</li>
<li><p>INFO</p>
</li>
<li><p>WARNING</p>
</li>
<li><p>ERROR</p>
</li>
<li><p>CRITICAL</p>
</li>
</ul>
<p>Let’s log a simple message at each level:</p>
<pre><code class="lang-bash">logging.debug(<span class="hljs-string">"This is a debug message"</span>)
logging.info(<span class="hljs-string">"This is an info message"</span>)
logging.warning(<span class="hljs-string">"This is a warning message"</span>)
logging.error(<span class="hljs-string">"This is an error message"</span>)
logging.critical(<span class="hljs-string">"This is a critical message"</span>)
</code></pre>
<p>When you run this, you’ll see a message printed to the console, similar to this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738500126070/a2a395c3-5cbe-4f94-bea2-d871cfc1529e.png" alt="Terminal showing Python log messages." class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>You might wonder why you don’t see the <strong>DEBUG</strong> and <strong>INFO</strong> messages. The default logging level prevents this.</p>
<p>By default, the logging level is set to <code>WARNING</code>. This means that only messages with a severity of <code>WARNING</code> or higher will be displayed (that is, <code>WARNING</code>, <code>ERROR</code>, and <code>CRITICAL</code>).</p>
<h3 id="heading-step-3-set-up-the-basic-configuration"><strong>Step 3:</strong> Set Up the Basic Configuration</h3>
<p>To see the <code>debug</code> and <code>info</code> messages, we need to set the logging level <code>DEBUG</code> before running the code.</p>
<p>This means we need to configure the logs. So to do this, use the method <code>basicConfig</code> below:</p>
<pre><code class="lang-bash">logging.basicConfig(level=logging.DEBUG)
</code></pre>
<p>This basic configuration allows you to log messages at the <strong>DEBUG</strong> level or higher. You can change the level depending on the type of logs you want.</p>
<p>Now, all logs are printing:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738500423798/96b65689-f0e4-4663-9d1a-1dc7147e964e.png" alt="log messages: debug, info, warning, error, critical." class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<h3 id="heading-step-4-log-to-a-file">Step 4: Log to a File</h3>
<p>Now, let’s save these logs in a file so we can keep track of errors, as well as when they occurred. To do this, update the configuration:</p>
<pre><code class="lang-bash">logging.basicConfig(filename=<span class="hljs-string">'data_log.log'</span>, level=logging.DEBUG, 
                    format=<span class="hljs-string">'%(asctime)s - %(levelname)s - %(message)s'</span>)
</code></pre>
<p>Here:</p>
<ul>
<li><p><code>asctime</code> – The time when the event occurred.</p>
</li>
<li><p><code>levelname</code> – The type of the log (for example, <strong>DEBUG</strong>, <strong>INFO</strong>).</p>
</li>
<li><p><code>message</code> – The message we display.</p>
</li>
</ul>
<p>Now, when you run the program, the log file will generate and save your logs, showing the exact timing, error type, and message. Like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738500713832/7895f1db-8740-494a-86dd-86020f4f5569.png" alt="Log file with debug, info, warning, error, critical messages" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-use-loggers-for-more-control">How to Use Loggers for More Control</h2>
<p>If you’re working on a large project, you might want a utility logger that you can use anywhere in the code. Let’s create this custom logger.</p>
<p>First, we’ll update the <code>basicConfig</code> to add the filename, line number, and ensure it writes everything, even special characters:</p>
<pre><code class="lang-bash">logging.basicConfig(
        filename=log_file,
        level=logging.DEBUG,
        format=<span class="hljs-string">'%(asctime)s - %(levelname)s - %(filename)s:%(lineno)d - %(message)s'</span>, 
        filemode=<span class="hljs-string">'w'</span>,
        encoding=<span class="hljs-string">'utf-8'</span> 
    )
</code></pre>
<p>Explanation:</p>
<ul>
<li><p><code>encoding='utf-8'</code> — Ensures special characters are logged.</p>
</li>
<li><p><code>%(filename)s:%(lineno)d</code> — Logs the filename and line number where the log was generated.</p>
</li>
</ul>
<p>Now, let’s set up a custom console logger:</p>
<pre><code class="lang-bash">  console_handler = logging.StreamHandler()
  console_handler.setLevel(logging.DEBUG)
  console_formatter = logging.Formatter(<span class="hljs-string">'%(asctime)s - %(levelname)s - %(filename)s:%(lineno)d - %(message)s'</span>)  <span class="hljs-comment"># Added line number</span>
  console_handler.setFormatter(console_formatter)


   logging.getLogger().addHandler(console_handler)
</code></pre>
<p>This setup does the following:</p>
<ul>
<li><p><code>console_handler</code>: Sends log messages to the console (stdout).</p>
</li>
<li><p><code>console_formatter</code>: Formats the log message with time, level, filename, line number, and the message.</p>
</li>
<li><p><code>logging.getLogger().addHandler(console_handler)</code>: Adds the custom handler to the root logger, so the log messages are printed to the console.</p>
</li>
</ul>
<h3 id="heading-full-example-code">Full Example Code</h3>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> logging
<span class="hljs-keyword">import</span> os
<span class="hljs-keyword">from</span> datetime <span class="hljs-keyword">import</span> datetime

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">setup_daily_logger</span>():</span>
    base_dir = os.path.dirname(os.path.abspath(__file__))
    log_dir = os.path.join(base_dir, <span class="hljs-string">'logs'</span>)  
    os.makedirs(log_dir, exist_ok=<span class="hljs-literal">True</span>)


    current_time = datetime.now().strftime(<span class="hljs-string">"%m_%d_%y_%I_%M_%p"</span>)
    log_file = os.path.join(log_dir, <span class="hljs-string">f"<span class="hljs-subst">{current_time}</span>.log"</span>)


    logging.basicConfig(
        filename=log_file,
        level=logging.DEBUG,
        format=<span class="hljs-string">'%(asctime)s - %(levelname)s - %(filename)s:%(lineno)d - %(message)s'</span>, 
        filemode=<span class="hljs-string">'w'</span>,
        encoding=<span class="hljs-string">'utf-8'</span> 
    )


    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.DEBUG)
    console_formatter = logging.Formatter(<span class="hljs-string">'%(asctime)s - %(levelname)s - %(filename)s:%(lineno)d - %(message)s'</span>)  <span class="hljs-comment"># Added line number</span>
    console_handler.setFormatter(console_formatter)


    logging.getLogger().addHandler(console_handler)


    <span class="hljs-keyword">return</span> logging.getLogger(__name__)
</code></pre>
<h3 id="heading-what-happens-now">What Happens Now?</h3>
<p>Now, whenever you run the program, a new log file will be created in the <code>logs</code> folder. Each time the program is executed, a new log file with a unique timestamp will be generated.</p>
<p>Like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738503550743/1ad9fb99-762a-4ca9-a189-58d044955617.png" alt="custom log used in app.py" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>These logs will give you a clear picture of your program’s behavior and help with debugging.</p>
<p>I hope this article helped you get a clearer picture of logs and their importance in programming.</p>
<h1 id="heading-practical-real-world-examples">Practical Real-World Examples</h1>
<p>Now that you understand what logs are and how to set them up in Python, let’s look at real-world use cases.</p>
<h2 id="heading-1-bot-scraping-koreas-largest-property-website">1. Bot: Scraping Korea’s Largest Property Website</h2>
<p>Here’s an example of a bot designed to scrape Korea’s biggest property website.</p>
<ul>
<li><p>The logs show every step the bot takes, making it easier to track progress.</p>
</li>
<li><p>If an error occurs at any step, it gets recorded in the log file.</p>
</li>
<li><p>Even if the bot crashes, I can check the logs to pinpoint where things went wrong.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739037891010/69a8b5ae-d202-4466-add0-bb2ace28230a.png" alt="Log file with INFO messages showing city and town extraction details." class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739037833210/bf9ceba0-2caf-48c6-bdb8-ac2d9eb901bd.png" alt="Log file with INFO messages showing city and town extraction details." class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>One of the methods in this bot’s class uses logging to track whether the bot correctly selects the province.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739038058017/6153c909-477d-4cd6-b493-124b96bc595f.png" alt="select_province function that utilizes logging" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>Here:</p>
<ul>
<li><p>If an error or warning occurs, it’s saved in the log file.</p>
</li>
<li><p>Later, you can review the logs and find out exactly what happened</p>
</li>
</ul>
<h2 id="heading-2-bot-scraping-facebook-groups">2. Bot: Scraping Facebook Groups</h2>
<p>Now, let’s see how logging helps in a Facebook group scraper.</p>
<h5 id="heading-error-tracking">Error Tracking</h5>
<ul>
<li><p>At one point, the bot failed due to an error.</p>
</li>
<li><p>Since we had logging in place, the error was saved in the log file.</p>
</li>
<li><p>This allows you to quickly find out what went wrong.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739038507530/9662bed7-a124-4dd8-94a9-9d657ec022a1.png" alt="Error log file" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>Here, you see the exact filename and line number where the error occurs.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739038826232/ce717b49-e532-4c5f-a40d-955591aa27a2.png" alt="Logs file shows success logs" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>Once we identified and fixed the issue, the bot started working again.</p>
<p>It captures every detail in the log, saving hours of debugging by pinpointing where errors occur.</p>
<h5 id="heading-debugging-made-easy">Debugging Made Easy</h5>
<ul>
<li><p>The logs recorded every detail of the bot’s execution.</p>
</li>
<li><p>This can save you hours of debugging because you’ll know exactly where the error occurred.</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Logging is one of those things no one thinks about until something breaks. But when it does, logs become your best friend.</p>
<p>Remember:</p>
<ul>
<li><p>Logging isn’t just for error tracking—it helps you monitor your program’s flow.</p>
</li>
<li><p>Instead of guessing what went wrong, check the logs. The answer is usually right there.</p>
</li>
</ul>
<p>Make sure to add logging to your code. You’ll thank yourself later!</p>
<p><strong>Stay Connected - @syedamahamfahim 🐬</strong></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Handle KeyErrors in Python – with Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ When working with dictionaries in Python, you’d often run into KeyError exceptions. Dictionaries are built-in data structures of key value pairs. So you can look up a value—in constant time—using the corresponding key like so: dict[key] returns value... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-handle-keyerror-exceptions-in-python/</link>
                <guid isPermaLink="false">66bb8b36d2bda3e43154919e</guid>
                
                    <category>
                        <![CDATA[ error handling ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Bala Priya C ]]>
                </dc:creator>
                <pubDate>Mon, 17 Jun 2024 18:24:14 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/06/fimg-key-errors.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>When working with dictionaries in Python, you’d often run into <code>KeyError</code> exceptions.</p>
<p>Dictionaries are built-in data structures of key value pairs. So you can look up a value—in constant time—using the corresponding key like so: <code>dict[key]</code> returns <code>value</code>. But what if the key doesn't exist in the dictionary? Well, that’s when you get a <code>KeyError</code> in Python.</p>
<p>There are few different ways you can handle such <code>KeyError</code> exceptions. You can handle them explicitly or use certain dictionary methods to set default values for missing keys. And in this tutorial, we’ll look at the following methods by coding a simple example:</p>
<ul>
<li>Using <code>try-except</code> blocks</li>
<li>Using the dictionary method <code>get()</code></li>
<li>Using <code>defaultdict</code> from the <code>collections</code> module</li>
</ul>
<p>Let's get started.</p>
<h2 id="heading-1-how-to-handle-keyerror-exceptions-with-try-except-blocks">1. How to Handle KeyError Exceptions with <code>try-except</code> Blocks</h2>
<p>Let's start by reviewing when KeyErrors occur and how we can handle these exceptions using <code>try-except</code> blocks.</p>
<h3 id="heading-when-does-a-keyerror-occur">When Does a KeyError Occur?</h3>
<p>In Python, a <code>KeyError</code> exception occurs when you try to access the value corresponding to a key that doesn't exist. Consider the following <code>books</code> dictionary:</p>
<pre><code class="lang-python">books = {
    <span class="hljs-string">"1984"</span>: <span class="hljs-string">"George Orwell"</span>,
    <span class="hljs-string">"To Kill a Mockingbird"</span>: <span class="hljs-string">"Harper Lee"</span>,
    <span class="hljs-string">"The Great Gatsby"</span>: <span class="hljs-string">"F. Scott Fitzgerald"</span>
}
</code></pre>
<p>In the <code>books</code> dictionary, the keys are titles of the books and the values are the names of the authors. So you can look up the author of a book using the title as the key.</p>
<p>Now let's try to look up the author of a book that doesn't exist in the dictionary:</p>
<pre><code class="lang-python">print(books[<span class="hljs-string">"Brave New World"</span>])
</code></pre>
<p>You’ll run into the following <code>KeyError</code> exception:</p>
<pre><code>Traceback (most recent call last):
  File <span class="hljs-string">"/home/balapriya/keyerror/main.py"</span>, line <span class="hljs-number">7</span>, <span class="hljs-keyword">in</span> &lt;<span class="hljs-built_in">module</span>&gt;
    print(books[<span class="hljs-string">"Brave New World"</span>])
          ~~~~~^^^^^^^^^^^^^^^^^^^
KeyError: <span class="hljs-string">'Brave New World'</span>
</code></pre><h3 id="heading-how-to-handle-keyerror-exceptions">How to Handle KeyError Exceptions</h3>
<p>You can explicitly handle such <code>KeyError</code> exceptions using <code>try-except</code> blocks like so:</p>
<pre><code class="lang-python"><span class="hljs-keyword">try</span>:
    value = dictionary[key]
<span class="hljs-keyword">except</span> KeyError:
    value = default_value
</code></pre>
<p>Here:</p>
<ul>
<li>We wrap the block of code that might raise an exception within the try block. In this case, we attempt to access the value associated with the key.</li>
<li>If a <code>KeyError</code> is raised, we handle it in the <code>except</code> block by assigning a default value.</li>
</ul>
<p>For the <code>books</code> dictionary example, we have:</p>
<pre><code class="lang-python">books = {
    <span class="hljs-string">"1984"</span>: <span class="hljs-string">"George Orwell"</span>,
    <span class="hljs-string">"To Kill a Mockingbird"</span>: <span class="hljs-string">"Harper Lee"</span>,
    <span class="hljs-string">"The Great Gatsby"</span>: <span class="hljs-string">"F. Scott Fitzgerald"</span>
}

<span class="hljs-keyword">try</span>:
    <span class="hljs-comment"># Try to access the key "Brave New World"</span>
    author = books[<span class="hljs-string">"Brave New World"</span>]  
    <span class="hljs-comment"># Catch the KeyError if the key does not exist</span>
<span class="hljs-keyword">except</span> KeyError:  
    author = <span class="hljs-string">"Book not found"</span>  

print(author)
</code></pre>
<p>We try to look up the author of “Brave New World'' again. But this time the <code>KeyError</code> triggers the except block, and we get “Book not found”.</p>
<pre><code class="lang-python">Output &gt;&gt;&gt; Book <span class="hljs-keyword">not</span> found
</code></pre>
<h2 id="heading-2-how-to-handle-keyerrors-using-the-get-dictionary-method">2. How to Handle KeyErrors Using the <code>get()</code> Dictionary Method</h2>
<p>Another way to handle missing keys without raising an exception is using the <code>get()</code> dictionary method. </p>
<p>You can use the <code>get()</code> method on any valid dictionary object. The <code>get()</code> method returns the value for a given key if it exists – otherwise, it returns a specified default value. You can use it like so:</p>
<pre><code class="lang-python">value = dictionary.get(key, default_value)
</code></pre>
<p>In essence, the <code>get()</code> method tries to <em>get</em> the value for the specified key:</p>
<ul>
<li>If the key exists, it returns the corresponding value. </li>
<li>If the key does not exist, it returns the <code>default_value</code>.</li>
</ul>
<p>Let's now use the <code>get()</code> method on the books dictionary. We pass in "Book not found" as the default value in the method call. </p>
<pre><code class="lang-python">books = {
    <span class="hljs-string">"1984"</span>: <span class="hljs-string">"George Orwell"</span>,
    <span class="hljs-string">"To Kill a Mockingbird"</span>: <span class="hljs-string">"Harper Lee"</span>,
    <span class="hljs-string">"The Great Gatsby"</span>: <span class="hljs-string">"F. Scott Fitzgerald"</span>
}

<span class="hljs-comment"># Try to get the value for "Brave New World"</span>
author = books.get(<span class="hljs-string">"Brave New World"</span>, <span class="hljs-string">"Book not found"</span>)  
print(author)
</code></pre>
<p>As expected, you should get the following output:</p>
<pre><code class="lang-python">Output &gt;&gt;&gt; Book <span class="hljs-keyword">not</span> found
</code></pre>
<p><strong>Note</strong>: The <code>get()</code> method does not modify the original dictionary. If you also want to add the missing key with a default value, you can use the <code>setdefault()</code> method instead with the syntax <code>dictionary.setdefault(key,default_value)</code>.</p>
<h2 id="heading-3-how-to-use-defaultdict-from-the-collections-module">3. How to Use <code>defaultdict</code> from the <code>collections</code> Module</h2>
<p>A (much) cleaner way to handle KeyErrors is using <code>defaultdict</code> from Python’s <code>collections</code> module. Defaultdict extends the capabilities of Python's built-in dictionary by allowing you to provide a default value for keys that haven't been explicitly set.</p>
<p>The <code>defaultdict</code> constructor takes a default factory function as an argument. This factory function is called <em>without</em> arguments to provide a default value for a non-existent key. </p>
<p>The syntax for creating a <code>defaultdict</code> is as follows:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> collections <span class="hljs-keyword">import</span> defaultdict

<span class="hljs-comment"># Syntax</span>
defaultdict(default_factory)
</code></pre>
<p>Let's create a <code>defaultdict</code> from the <code>books</code> dictionary as shown:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> collections <span class="hljs-keyword">import</span> defaultdict

books = {
    <span class="hljs-string">"1984"</span>: <span class="hljs-string">"George Orwell"</span>,
    <span class="hljs-string">"To Kill a Mockingbird"</span>: <span class="hljs-string">"Harper Lee"</span>,
    <span class="hljs-string">"The Great Gatsby"</span>: <span class="hljs-string">"F. Scott Fitzgerald"</span>
}

books_default = defaultdict(<span class="hljs-keyword">lambda</span>: <span class="hljs-string">"Book not found"</span>,books)  
<span class="hljs-comment"># Access the key "Brave New World"</span>
author = books_default[<span class="hljs-string">"Brave New World"</span>]  
print(author)
</code></pre>
<p>For the default factory function, we use a simple lambda function that returns the string "Book not found". This function is called whenever you try to access a key that's not present in the dictionary.</p>
<p>Running the above snippet should also give you:</p>
<pre><code>Output &gt;&gt;&gt; Book not found
</code></pre><p>Using <code>defaultdict</code> can be especially helpful when you need to dynamically access many keys.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>And that's a wrap! I hope you learned how to handle KeyError exceptions in Python. Let's review what we learned:</p>
<ul>
<li>To explicitly handle a <code>KeyError</code>, you can wrap the dictionary access code with a <code>try</code> block, and catch the <code>KeyError</code> in the <code>except</code> block.</li>
<li>Use the <code>get()</code> method to access the value of a key, with the option to return a default value if the key does not exist.</li>
<li>You can initialize a <code>defaultdict</code> from the <code>collections</code> module with a factory function that returns the default value.</li>
</ul>
<p>If you'd like to learn about exception handling in Python, read <a target="_blank" href="https://www.freecodecamp.org/news/python-try-and-except-statements-how-to-handle-exceptions-in-python/">Python Try and Except Statements - How to Handle Exceptions in Python</a>. </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Error Handling in Python – try, except, else, & finally Explained with Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ By Gage Schaffer Just recently, my manager tasked me to create an automatic report. I designed the report to be simple. It included a few numbers from a database and some basic mathematical operations. I was excited to finally be able to show off my ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/error-handling-in-python-introduction/</link>
                <guid isPermaLink="false">66d45edb7df3a1f32ee7f857</guid>
                
                    <category>
                        <![CDATA[ error handling ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 11 Apr 2024 00:09:53 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/04/game-over-screen.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Gage Schaffer</p>
<p>Just recently, my manager tasked me to create an automatic report. I designed the report to be simple. It included a few numbers from a database and some basic mathematical operations. I was excited to finally be able to show off my <em>amazing</em> Python skills to the company.</p>
<p>I finished and shipped the product. Everything was great. At least, until about two weeks later. My report began failing randomly due to a divide-by-zero error. Cue the laugh track.</p>
<p>My short story is absent details, but it should highlight the importance of handling edge cases and errors when composing programs. This report should have been an opportunity to show off my Python prowess. Yet, it turned into a bit of an embarrassing, fall-on-my-face moment.</p>
<p>So, let’s take a moment to learn the basics of error handling using Python’s standard library. I’m going to highlight some of the things you need to get started.</p>
<p>Before you start handling exceptions, you should have a good grasp of Python fundamentals. You’ll need to know why the exceptions are being thrown to deal with them!</p>
<h3 id="heading-heres-what-well-cover">Here's what we'll cover:</h3>
<ol>
<li><a class="post-section-overview" href="#heading-try-and-except-statements-in-python">Try and Except Statements in Python</a></li>
<li><a class="post-section-overview" href="#heading-conditional-execution-with-the-else-clause">Conditional Execution with the Else Clause</a></li>
<li><a class="post-section-overview" href="#heading-built-in-exceptions">Built-in Exceptions</a></li>
<li><a class="post-section-overview" href="#heading-custom-exceptions">Custom Exceptions</a></li>
<li><a class="post-section-overview" href="#heading-performance-considerations">Performance Considerations</a></li>
</ol>
<h2 id="heading-try-and-except-statements-in-python">Try and Except Statements in Python</h2>
<p>The <code>try</code> and <code>except</code> statements are the primary method of dealing with exceptions. They look something like this:</p>
<pre><code class="lang-python">x = <span class="hljs-number">0</span>
<span class="hljs-keyword">try</span>:
    print(<span class="hljs-number">5</span> / x)
<span class="hljs-keyword">except</span> ZeroDivisionError:
    print(<span class="hljs-string">"Something went wrong"</span>)

<span class="hljs-comment"># Something went wrong</span>
</code></pre>
<p>Let’s review the above code so we are on the same page:</p>
<ol>
<li>Line 1 assigns the value 0 to a variable <code>x</code></li>
<li>Lines 2 and 3 open a <code>try</code> clause and attempt to divide 5 by the variable <code>x</code></li>
<li>Lines 4 and 5 open an <code>except</code> clause for any <code>ZeroDivisionError</code> and instruct     the program to print a message should we try to divide anything by 0</li>
</ol>
<p>You likely notice the issue. My variable <code>x</code> has the value 0, and I am trying to divide 5 by <code>x</code>. The best mathematicians in the world can’t divide by 0, and neither can Python. So, what happens?</p>
<p>If we do not handle the error, the program will immediately terminate upon trying to divide 5 by <code>x</code>. Since programs do not know what to do with exceptions without explicit instructions, we created the <code>except</code> clause on line 4 and provided the steps for the program to take in the event of dividing something by 0.</p>
<p>That’s the whole idea behind handling exceptions: you need to tell the program what to do when it has an error that it cannot simply ignore. Let’s look at how the <code>try</code> and <code>except</code> clauses work.</p>
<h3 id="heading-breaking-down-the-try-statement">Breaking Down the Try Statement</h3>
<p><code>Try</code> and <code>Except</code> statements follow a pattern that allows you to reliably handle problems in your code. Let’s go over the pattern.</p>
<p>The first step that happens is, the code in the <code>try</code> clause attempts to execute.</p>
<p>After that, we have three possibilities:</p>
<h4 id="heading-no-errors-in-the-try-clause">No Errors in the Try Clause</h4>
<p>If the code in the <code>try</code> clause executes <strong>without any errors</strong>, the program will:</p>
<ol>
<li>Execute the <code>try</code> clause</li>
<li>Skip all <code>except</code> clauses</li>
<li>Continue running as normal</li>
</ol>
<pre><code class="lang-python">x = <span class="hljs-number">1</span>
<span class="hljs-keyword">try</span>:
    print(<span class="hljs-number">5</span> / x)
<span class="hljs-keyword">except</span> ZeroDivisionError:
    print(<span class="hljs-string">"Something went wrong"</span>)

print(<span class="hljs-string">"I am executing after the try clause!"</span>)

<span class="hljs-comment"># 5.0</span>
<span class="hljs-comment"># I am executing after the try clause!</span>
</code></pre>
<p>You can see that, in this modified example, there are no issues in the <code>try</code> clause (Lines 3 and 4). The code will execute, the <code>except</code> clause will be skipped, and the program will resume execution after the <code>try</code> and <code>except</code> statements conclude.</p>
<h4 id="heading-errors-in-the-try-clause-and-the-exception-is-specified">Errors in the Try Clause and the Exception is Specified</h4>
<p>If the code in the <code>try</code> clause <strong>does throw an exception</strong> and <strong>the type of exception is specified after any <code>except</code> keyword</strong>, the program will:</p>
<ol>
<li>Skip the remaining code in the <code>try</code> clause</li>
<li>Execute any code in the matching <code>except</code> clause</li>
<li>Continue running as normal</li>
</ol>
<pre><code class="lang-python">x = <span class="hljs-number">0</span>
<span class="hljs-keyword">try</span>:
    print(<span class="hljs-number">5</span> / x)
<span class="hljs-keyword">except</span>:
    print(<span class="hljs-string">"Something went wrong"</span>)

print(<span class="hljs-string">"I am executing after the try clause!"</span>)

<span class="hljs-comment"># Something went wrong</span>
<span class="hljs-comment"># I am executing after the try clause!</span>
</code></pre>
<p>Back to my first example, I changed our variable <code>x</code> back to the value 0 and tried to divide 5 by <code>x</code>. This produces a <code>ZeroDivisionError</code>. Since my <code>except</code> statement specifies this type of exception, the code in that clause executes before the program resumes running as normal.</p>
<h4 id="heading-errors-in-the-try-clause-and-the-exception-is-not-specified">Errors in the Try Clause and the Exception is not Specified</h4>
<p>Finally, if the program throws an exception in the <code>try</code> clause, <strong>but the exception is not specified in any <code>except</code> statements</strong>, then the program will:</p>
<ol>
<li>Stop the execution of the program and throw the error</li>
</ol>
<pre><code class="lang-python">x = <span class="hljs-number">0</span>
<span class="hljs-keyword">try</span>:
    print(<span class="hljs-number">5</span> / y)
<span class="hljs-keyword">except</span>:
    print(<span class="hljs-string">"Something went wrong"</span>)

print(<span class="hljs-string">"I am executing after the try clause!"</span>)

<span class="hljs-comment"># NameError: name 'y' is not defined</span>
</code></pre>
<p>In the above example, I’m trying to divide 5 by the variable <code>y</code>, which does not exist. This raises a <code>NameError</code>. I don’t specify to the program how to handle <code>NameError</code>s, so the only option is to terminate itself.</p>
<h3 id="heading-cleaning-up">Cleaning Up</h3>
<p><code>Try</code> and <code>except</code> are the main tools in handling errors, but an optional clause that you can use is named <code>finally</code>. The <code>finally</code> clause will always execute, whether there is an error or not.</p>
<pre><code class="lang-python">x = <span class="hljs-number">0</span>
<span class="hljs-keyword">try</span>:
    print(<span class="hljs-number">5</span> / x)
<span class="hljs-keyword">except</span> ZeroDivisionError:
    print(<span class="hljs-string">"I am the except clause!"</span>)
<span class="hljs-keyword">finally</span>:
    print(<span class="hljs-string">"I am the finally clause!"</span>)

print(<span class="hljs-string">"I am executing after the try clause!"</span>)

<span class="hljs-comment"># I am the except clause!</span>
<span class="hljs-comment"># I am the finally clause!</span>
<span class="hljs-comment"># I am executing after the try clause!</span>
</code></pre>
<p>In this example, I have created our favorite <code>ZeroDivisionError</code>. You can see that the order of execution is:</p>
<ol>
<li>The <code>except</code> clause</li>
<li>The <code>finally</code> clause</li>
<li>Any code afterwards</li>
</ol>
<p>Once we fix the <code>try</code> clause to no longer throw an error, you’ll still see a similar order of execution. Instead of the <code>except</code> clause running, the <code>try</code> clause will execute. </p>
<pre><code class="lang-python">x = <span class="hljs-number">1</span>
<span class="hljs-keyword">try</span>:
    print(<span class="hljs-number">5</span> / x)
<span class="hljs-keyword">except</span> ZeroDivisionError:
    print(<span class="hljs-string">"I am the except clause!"</span>)
<span class="hljs-keyword">finally</span>:
    print(<span class="hljs-string">"I am the finally clause!"</span>)

print(<span class="hljs-string">"I am executing after the try clause!"</span>)

<span class="hljs-comment"># 5.0</span>
<span class="hljs-comment"># I am the finally clause!</span>
<span class="hljs-comment"># I am executing after the try clause!</span>
</code></pre>
<p>You’ll notice that the only difference is that <code>try</code> clause is successfully executed because there are no exceptions thrown. The <code>finally</code> clause and the code afterwards execute as you would expect.</p>
<p>This is useful for some cases when you want to clean up no matter the outcome of your <code>try</code> and <code>except</code> clauses. Actions such as closing connections, closing files, and logging are great candidates for the <code>finally</code> clause.</p>
<h2 id="heading-conditional-execution-with-the-else-clause">Conditional Execution with the Else Clause</h2>
<p>The other optional clause is the <code>else</code> clause. The <code>else</code> clause is simple: if the code in the <code>try</code> clause executes without throwing an error, then the code in the <code>else</code> clause will also execute.</p>
<pre><code class="lang-python">x = <span class="hljs-number">1</span>
<span class="hljs-keyword">try</span>:
    print(<span class="hljs-number">5</span> / x)
<span class="hljs-keyword">except</span> ZeroDivisionError:
    print(<span class="hljs-string">"I am the except clause!"</span>)
<span class="hljs-keyword">else</span>:
    print(<span class="hljs-string">"I am the else clause!"</span>)
<span class="hljs-keyword">finally</span>:
    print(<span class="hljs-string">"I am the finally clause!"</span>)

print(<span class="hljs-string">"I am executing after the try clause!"</span>)

<span class="hljs-comment"># 5.0</span>
<span class="hljs-comment"># I am the else clause!</span>
<span class="hljs-comment"># I am the finally clause!</span>
<span class="hljs-comment"># I am executing after the try clause!</span>
</code></pre>
<p>The order of execution for this example is:</p>
<ol>
<li>The <code>try</code> clause</li>
<li>The <code>else</code> clause</li>
<li>The <code>finally</code> clause</li>
<li>Any code afterwards</li>
</ol>
<p>If we were to experience an exception or error in the <code>try</code> clause, the <code>else</code> clause would be ignored.</p>
<pre><code class="lang-python">x = <span class="hljs-number">0</span>
<span class="hljs-keyword">try</span>:
    print(<span class="hljs-number">5</span> / x)
<span class="hljs-keyword">except</span> ZeroDivisionError:
    print(<span class="hljs-string">"I am the except clause!"</span>)
<span class="hljs-keyword">else</span>:
    print(<span class="hljs-string">"I am the else clause!"</span>)
<span class="hljs-keyword">finally</span>:
    print(<span class="hljs-string">"I am the finally clause!"</span>)

print(<span class="hljs-string">"I am executing after the try clause!"</span>)

<span class="hljs-comment"># I am the except clause!</span>
<span class="hljs-comment"># I am the finally clause!</span>
<span class="hljs-comment"># I am executing after the try clause!</span>
</code></pre>
<h2 id="heading-built-in-exceptions">Built-in Exceptions</h2>
<p>You’ve seen me write about two different named exceptions so far: <code>NameError</code> and <code>ZeroDivisionError</code>. What if I needed other exceptions? </p>
<p>There is an entire list of Python’s exceptions that come with the standard library. These will probably suit almost every need that you have in handling any errors or exceptions.</p>
<p>Here are just a few that might be important:</p>
<ul>
<li><code>KeyError</code> – A key cannot be found in a dictionary</li>
<li><code>IndexError</code> – The index is out-of-bounds on an iterable object</li>
<li><code>TypeError</code> – A function or operation was used on the wrong type of object</li>
<li><code>OSError</code> – General operating system errors</li>
</ul>
<p>There are a whole lot more, which can be found in the Python documentation. I encourage to take a look. Not only will you be better at handling errors, but you will also explore what <em>actually</em> can go wrong with your Python programs.</p>
<h2 id="heading-custom-exceptions">Custom Exceptions</h2>
<p>If you need extended functionality, you can also define custom exceptions.</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ForError</span>(<span class="hljs-params">Exception</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, message</span>):</span>
        self.message = message

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">foo</span>(<span class="hljs-params">self</span>):</span>
        print(<span class="hljs-string">"bar"</span>)
</code></pre>
<p>In the above example, I create a new class and extend it from the Exception class. Now, I can write custom functionality and treat this exception as any other object.</p>
<pre><code class="lang-python"><span class="hljs-keyword">try</span>:
    <span class="hljs-keyword">raise</span> FooError(<span class="hljs-string">"This is a test error"</span>)
<span class="hljs-keyword">except</span> FooError <span class="hljs-keyword">as</span> e:
    e.foo()

<span class="hljs-comment"># bar</span>
</code></pre>
<p>Here, I raise my new <code>FooError</code> on purpose. I catch the <code>FooError</code> and give it an alias of <code>e</code>. Now, I can access my <code>foo()</code> method that I built into the class that I created. </p>
<p>This opens a whole plethora of possibilities when dealing with errors. Custom logging, more in-depth tracking, or whatever else you need can all be coded and created.</p>
<h2 id="heading-performance-considerations">Performance Considerations</h2>
<p>Now that you understand the basics of <code>try</code>, <code>except</code>, and exception objects, you can start considering using them in your code to gracefully handle errors. Are there any considerable impacts to code performance, though?</p>
<p>The short answer is no. With the release of Python 3.11, there is practically no speed reduction from using <code>try</code> and <code>except</code> statements when there are no thrown exceptions. </p>
<p>Catching errors did cause some slowdowns. But generally, catching these errors is better than having the entire program crash and burn.</p>
<p>In earlier versions of Python, using <code>try</code> and <code>except</code> clauses did cause some extra execution time. Keep this in mind if you’re not up to date.</p>
<h2 id="heading-to-recap">To Recap</h2>
<p>Thank you for reading this far. Your future self and customers will thank you for your error handling.</p>
<p>We went over the <code>try</code>, <code>except</code>, <code>else</code>, and <code>finally</code> clauses and their execution order and under what circumstances they are executed. We also reviewed the basics of creating custom exceptions. </p>
<p>The most important thing to remember is that the <code>try</code> and <code>except</code> clauses are the primary ways to catch errors, and you should be using them whenever you have risky, error-prone code.</p>
<p>Also, keep in mind that catching errors will make your code more resilient, and make you look like a much better coder.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Handle Errors in React Applications ]]>
                </title>
                <description>
                    <![CDATA[ Error handling is a critical aspect of developing user-friendly React applications. As a developer, you can't always predict or prevent errors, but you can certainly control how they are handled.  In this article, we'll explore practical and effectiv... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/effective-error-handling-in-react-applications/</link>
                <guid isPermaLink="false">66c4c3cbd788a9c53d88d2bc</guid>
                
                    <category>
                        <![CDATA[ error handling ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joan Ayebola ]]>
                </dc:creator>
                <pubDate>Wed, 13 Dec 2023 23:39:37 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/12/Pink-Purple-Business-Solution-Pitch-Deck-Presentation.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Error handling is a critical aspect of developing user-friendly React applications. As a developer, you can't always predict or prevent errors, but you can certainly control how they are handled. </p>
<p>In this article, we'll explore practical and effective strategies for handling errors in React applications. We'll cover various types of errors, from simple runtime errors to asynchronous errors, and discuss how to communicate these errors to users in a clear and friendly manner.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><a class="post-section-overview" href="#heading-different-types-of-react-errors">Different Types of React Errors</a><br>– <a class="post-section-overview" href="#heading-syntax-errors">Syntax errors</a><br>– <a class="post-section-overview" href="#heading-reference-errors">Reference errors</a><br>– <a class="post-section-overview" href="#heading-type-errors">Type errors</a><br>– <a class="post-section-overview" href="#heading-component-lifecycle-errors">Component lifecycle errors</a></li>
<li><a class="post-section-overview" href="#heading-how-to-implement-global-error-handling">How to Implement Global Error Handling</a><br>– <a class="post-section-overview" href="#heading-1-window-error-event">Window error event</a><br>– <a class="post-section-overview" href="#heading-2-unhandled-promise-rejections">Unhandled promise rejections</a></li>
<li><a class="post-section-overview" href="#heading-how-to-communicate-errors-to-users">How to Communicate Errors to Users</a></li>
<li><a class="post-section-overview" href="#heading-how-to-handle-asynchronous-errors">How to Handle Asynchronous Errors</a></li>
<li><a class="post-section-overview" href="#heading-how-to-log-errors-for-debugging">How to Log Errors for Debugging</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ol>
<h2 id="heading-different-types-of-react-errors">Different Types of React Errors</h2>
<h3 id="heading-syntax-errors">Syntax Errors:</h3>
<p>Syntax errors occur when there is a mistake in the structure of your code. They are typically caused by typos, missing or misplaced characters, or incorrect usage of programming language elements. These errors prevent the code from being parsed or compiled correctly, and as a result, the program cannot run.</p>
<p>Here's a breakdown of some common scenarios that lead to syntax errors:</p>
<h4 id="heading-mismatched-braces-parentheses-or-brackets">Mismatched Braces, Parentheses, or Brackets:</h4>
<pre><code class="lang-javascript"><span class="hljs-comment">// Incorrect</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myFunction</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">if</span> (<span class="hljs-literal">true</span>) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello World'</span>;
  }
}

<span class="hljs-comment">// Correct</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myFunction</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">if</span> (<span class="hljs-literal">true</span>) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello World'</span>);
  }
}
</code></pre>
<p>In this example, a syntax error occurs because there is a missing closing parenthesis in the <code>console.log</code> statement.</p>
<h4 id="heading-missing-semicolons">Missing Semicolons:</h4>
<pre><code class="lang-javascript"><span class="hljs-comment">// Incorrect</span>
<span class="hljs-keyword">const</span> greeting = <span class="hljs-string">'Hello World'</span>
<span class="hljs-built_in">console</span>.log(greeting)

<span class="hljs-comment">// Correct</span>
<span class="hljs-keyword">const</span> greeting = <span class="hljs-string">'Hello World'</span>;
<span class="hljs-built_in">console</span>.log(greeting);
</code></pre>
<p>JavaScript uses semicolons to separate statements. Omitting them can lead to syntax errors.</p>
<h4 id="heading-typos-and-misspelled-keywords">Typos and Misspelled Keywords:</h4>
<pre><code class="lang-javascript"><span class="hljs-comment">// Incorrect</span>
funtion myFunction() {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello World'</span>);
}

<span class="hljs-comment">// Correct</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myFunction</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello World'</span>);
}
</code></pre>
<p>Here, a syntax error occurs because the keyword <code>function</code> is misspelled as <code>funtion</code>.</p>
<h4 id="heading-unexpected-tokens">Unexpected Tokens:</h4>
<pre><code class="lang-javascript"><span class="hljs-comment">// Incorrect</span>
<span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
numbers.forEach(<span class="hljs-function"><span class="hljs-params">number</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(number))

<span class="hljs-comment">// Correct</span>
<span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
numbers.forEach(<span class="hljs-function"><span class="hljs-params">number</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(number));
</code></pre>
<p>This error might occur due to missing or extra characters that make the code structure unexpected.</p>
<p>To fix syntax errors, carefully review your code, paying close attention to the error messages provided by the development environment or browser console. These messages often indicate the line and position of the error, helping you identify and correct the mistake. </p>
<p>Remember that even a small syntax error can have a significant impact on your code's functionality, so it's crucial to address them promptly.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Corrected syntax</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">MyComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Hello World<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<h3 id="heading-reference-errors">Reference Errors:</h3>
<p>Reference errors occur in a program when you try to use a variable or function that has not been defined. Essentially, the interpreter or compiler cannot find the reference to the variable or function in the current scope, leading to a runtime error.</p>
<p>Here are a few common scenarios that result in reference errors:</p>
<h4 id="heading-undefined-variables">Undefined Variables:</h4>
<pre><code class="lang-javascript"><span class="hljs-comment">// Incorrect</span>
<span class="hljs-built_in">console</span>.log(myVariable);

<span class="hljs-comment">// Correct</span>
<span class="hljs-keyword">const</span> myVariable = <span class="hljs-string">'Hello World'</span>;
<span class="hljs-built_in">console</span>.log(myVariable);
</code></pre>
<p>In this example, a reference error occurs because <code>myVariable</code> is used before it's declared. Declaring the variable before using it resolves the issue.</p>
<h4 id="heading-misspelled-variables-or-functions">Misspelled Variables or Functions:</h4>
<pre><code class="lang-javascript"><span class="hljs-comment">// Incorrect</span>
<span class="hljs-keyword">const</span> greeting = <span class="hljs-string">'Hello World'</span>;
<span class="hljs-built_in">console</span>.log(greting);

<span class="hljs-comment">// Correct</span>
<span class="hljs-keyword">const</span> greeting = <span class="hljs-string">'Hello World'</span>;
<span class="hljs-built_in">console</span>.log(greeting);
</code></pre>
<p>A reference error can occur if there's a typo or misspelling in the variable or function name. In this case, correcting the spelling resolves the issue.</p>
<h4 id="heading-scoping-issues">Scoping Issues:</h4>
<pre><code class="lang-javascript"><span class="hljs-comment">// Incorrect</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myFunction</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">if</span> (<span class="hljs-literal">true</span>) {
    <span class="hljs-keyword">const</span> message = <span class="hljs-string">'Hello World'</span>;
  }
  <span class="hljs-built_in">console</span>.log(message);
}

<span class="hljs-comment">// Correct</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myFunction</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> message;
  <span class="hljs-keyword">if</span> (<span class="hljs-literal">true</span>) {
    message = <span class="hljs-string">'Hello World'</span>;
  }
  <span class="hljs-built_in">console</span>.log(message);
}
</code></pre>
<p>Here, a reference error occurs because <code>message</code> is defined within the scope of the <code>if</code> block and is not accessible outside of it. Moving the variable declaration to a broader scope fixes the issue.</p>
<h4 id="heading-accessing-properties-of-undefined-objects">Accessing Properties of Undefined Objects:</h4>
<pre><code class="lang-javascript"><span class="hljs-comment">// Incorrect</span>
<span class="hljs-keyword">const</span> person = { <span class="hljs-attr">name</span>: <span class="hljs-string">'John'</span> };
<span class="hljs-built_in">console</span>.log(person.age);

<span class="hljs-comment">// Correct</span>
<span class="hljs-keyword">const</span> person = { <span class="hljs-attr">name</span>: <span class="hljs-string">'John'</span> };
<span class="hljs-built_in">console</span>.log(person.age || <span class="hljs-string">'Age not available'</span>);
</code></pre>
<p>If you try to access a property of an object that is <code>undefined</code>, a reference error will occur. Using conditional checks or ensuring the object is properly initialized can prevent such errors.</p>
<p>To resolve reference errors, carefully check your code for the correct spelling and declaration of variables and functions. Make sure that variables are declared in the appropriate scope and that objects are properly initialized before accessing their properties. Pay attention to error messages in the console, as they often provide valuable information about the location and nature of the reference error.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Corrected reference</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">MyComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> undefinedVariable = <span class="hljs-string">"I am defined now!"</span>;
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{undefinedVariable}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<h3 id="heading-type-errors">Type Errors:</h3>
<p>Type errors occur in a program when an operation is performed on a value of an incorrect data type. </p>
<p>In JavaScript, which is a dynamically typed language, the data type of a variable is not explicitly declared, and it can change during runtime. </p>
<p>Type errors usually happen when an operation is attempted on a value that doesn't support that particular operation.</p>
<p>Here are some common scenarios that lead to type errors:</p>
<h4 id="heading-incorrect-data-type-for-an-operation">Incorrect Data Type for an Operation:</h4>
<pre><code class="lang-javascript"><span class="hljs-comment">// Incorrect</span>
<span class="hljs-keyword">const</span> number = <span class="hljs-number">42</span>;
<span class="hljs-keyword">const</span> result = number.toUpperCase();

<span class="hljs-comment">// Correct</span>
<span class="hljs-keyword">const</span> number = <span class="hljs-number">42</span>;
<span class="hljs-keyword">const</span> result = <span class="hljs-built_in">String</span>(number).toUpperCase();
</code></pre>
<p>Here, a type error occurs because <code>toUpperCase()</code> is a string method, and you can't directly apply it to a number. Converting the number to a string before applying the method resolves the issue.</p>
<h4 id="heading-mismatched-data-types-in-arithmetic-operations">Mismatched Data Types in Arithmetic Operations:</h4>
<pre><code class="lang-javascript"><span class="hljs-comment">// Incorrect</span>
<span class="hljs-keyword">const</span> result = <span class="hljs-string">'Hello'</span> * <span class="hljs-number">5</span>;

<span class="hljs-comment">// Correct</span>
<span class="hljs-keyword">const</span> result = <span class="hljs-string">'Hello'</span>.repeat(<span class="hljs-number">5</span>);
</code></pre>
<p>Attempting to perform a multiplication operation on a string and a number results in a type error. Using the appropriate string method fixes the issue.</p>
<h4 id="heading-undefined-or-null-values-in-operations">Undefined or Null Values in Operations:</h4>
<pre><code class="lang-javascript"><span class="hljs-comment">// Incorrect</span>
<span class="hljs-keyword">const</span> value = <span class="hljs-literal">undefined</span>;
<span class="hljs-keyword">const</span> result = value.toLowerCase();

<span class="hljs-comment">// Correct</span>
<span class="hljs-keyword">const</span> value = <span class="hljs-literal">undefined</span>;
<span class="hljs-keyword">const</span> result = <span class="hljs-built_in">String</span>(value).toLowerCase();
</code></pre>
<p>Trying to perform an operation on an <code>undefined</code> value can lead to a type error. Converting the value to a string before the operation resolves the error.</p>
<h4 id="heading-incorrect-usage-of-functions">Incorrect Usage of Functions:</h4>
<pre><code class="lang-javascript"><span class="hljs-comment">// Incorrect</span>
<span class="hljs-keyword">const</span> number = <span class="hljs-number">42</span>;
<span class="hljs-keyword">const</span> result = <span class="hljs-built_in">String</span>.toUpperCase(number);

<span class="hljs-comment">// Correct</span>
<span class="hljs-keyword">const</span> number = <span class="hljs-number">42</span>;
<span class="hljs-keyword">const</span> result = <span class="hljs-built_in">String</span>(number).toUpperCase();
</code></pre>
<p>Using a function incorrectly, such as trying to call <code>toUpperCase()</code> on the <code>String</code> constructor, results in a type error. The correct usage involves creating a string instance first.</p>
<p>To address type errors, it's essential to understand the data types of your variables and the operations you are performing. You can use functions or methods to explicitly convert values to the desired data type before performing operations. Pay attention to error messages in the console, as they often indicate the nature and location of the type error in your code.</p>
<h3 id="heading-component-lifecycle-errors">Component Lifecycle Errors:</h3>
<p>Component Lifecycle Errors in React occur when there are issues related to the lifecycle methods of a React component. </p>
<p>React components go through various phases during their lifecycle, and each phase is associated with specific methods. If these methods are not used correctly or if there are errors within them, it can lead to unexpected behavior and errors in your React application.</p>
<p>The React component lifecycle consists of three main phases:</p>
<p><strong>Mounting Phase:</strong></p>
<ul>
<li><code>constructor()</code></li>
<li><code>static getDerivedStateFromProps()</code></li>
<li><code>render()</code></li>
<li><code>componentDidMount()</code></li>
</ul>
<p><strong>Updating Phase:</strong></p>
<ul>
<li><code>static getDerivedStateFromProps()</code></li>
<li><code>shouldComponentUpdate()</code></li>
<li><code>render()</code></li>
<li><code>getSnapshotBeforeUpdate()</code></li>
<li><code>componentDidUpdate()</code></li>
</ul>
<p><strong>Unmounting Phase:</strong></p>
<ul>
<li><code>componentWillUnmount()</code></li>
</ul>
<p>Here are some common scenarios that may result in Component Lifecycle Errors:</p>
<h4 id="heading-using-setstate-improperly">Using <code>setState</code> Improperly:</h4>
<pre><code class="lang-javascript"><span class="hljs-comment">// Incorrect</span>
componentDidMount() {
  <span class="hljs-built_in">this</span>.setState({ <span class="hljs-attr">data</span>: fetchData() });
}
</code></pre>
<p>Using <code>setState</code> directly inside <code>componentDidMount</code> without considering asynchronous behavior can lead to issues. It's recommended to use a callback function to ensure that <code>setState</code> is called after the data is fetched.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Correct</span>
componentDidMount() {
  fetchData().then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
    <span class="hljs-built_in">this</span>.setState({ data });
  });
}
</code></pre>
<h4 id="heading-not-handling-asynchronous-operations-correctly">Not Handling Asynchronous Operations Correctly:</h4>
<pre><code class="lang-javascript"><span class="hljs-comment">// Incorrect</span>
componentDidUpdate() {
  fetchData().then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
    <span class="hljs-built_in">this</span>.setState({ data });
  });
}
</code></pre>
<p>Performing asynchronous operations directly inside <code>componentDidUpdate</code> can lead to infinite loops. It's crucial to conditionally check if an update is needed and handle asynchronous operations appropriately.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Correct</span>
componentDidUpdate(prevProps, prevState) {
  <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.props.someValue !== prevProps.someValue) {
    fetchData().then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
      <span class="hljs-built_in">this</span>.setState({ data });
    });
  }
}
</code></pre>
<h4 id="heading-not-cleaning-up-resources-in-componentwillunmount">Not Cleaning Up Resources in <code>componentWillUnmount</code>:</h4>
<pre><code class="lang-javascript"><span class="hljs-comment">// Incorrect</span>
componentWillUnmount() {
  <span class="hljs-built_in">clearInterval</span>(<span class="hljs-built_in">this</span>.intervalId);
}
</code></pre>
<p>Forgetting to clean up resources, such as intervals or event listeners, in the <code>componentWillUnmount</code> method can lead to memory leaks. Always make sure to clear any resources to avoid unexpected behavior.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Correct</span>
componentWillUnmount() {
  <span class="hljs-built_in">clearInterval</span>(<span class="hljs-built_in">this</span>.intervalId);
}
</code></pre>
<p>Understanding and properly implementing React component lifecycle methods is crucial to avoid errors and ensure that your components behave as expected throughout their lifecycle. Always refer to the official React documentation for the latest guidelines on component lifecycles.</p>
<h2 id="heading-how-to-implement-global-error-handling">How to Implement Global Error Handling</h2>
<h3 id="heading-1-window-error-event">1. <strong>Window Error Event:</strong></h3>
<p>The <code>window.onerror</code> event handler in JavaScript allows you to capture and handle unhandled errors at the global level in a web application. This event is triggered whenever an uncaught exception occurs, and it provides a way to log or handle these errors centrally. It's a powerful tool for global error handling and debugging.</p>
<p>Here's how you can use <code>window.onerror</code> to implement global error handling:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">window</span>.onerror = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">message, source, lineno, colno, error</span>) </span>{
  <span class="hljs-comment">// Log the error details or send them to a logging service</span>
  <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error:'</span>, message);
  <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Source:'</span>, source);
  <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Line Number:'</span>, lineno);
  <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Column Number:'</span>, colno);
  <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error Object:'</span>, error);

  <span class="hljs-comment">// Return true to prevent the default browser error handling</span>
  <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
};
</code></pre>
<p>Let's break down the parameters of the <code>window.onerror</code> callback function:</p>
<ul>
<li><code>message</code>: A string containing the error message.</li>
<li><code>source</code>: A string representing the URL of the script where the error occurred.</li>
<li><code>lineno</code>: An integer indicating the line number where the error occurred.</li>
<li><code>colno</code>: An integer indicating the column number where the error occurred.</li>
<li><code>error</code>: An error object containing additional information about the error (if available).</li>
</ul>
<p>Inside the <code>window.onerror</code> handler, you can perform various actions, such as logging the error details to a server, displaying a user-friendly error message, or performing additional cleanup. The <code>return true;</code> statement is used to prevent the default browser error handling, allowing you to handle errors in a custom way.</p>
<p>Here's an example of using <code>window.onerror</code> to log errors to a remote server:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">window</span>.onerror = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">message, source, lineno, colno, error</span>) </span>{
  <span class="hljs-comment">// Log the error details to a remote server</span>
  <span class="hljs-keyword">const</span> errorData = {
    message,
    source,
    lineno,
    colno,
    <span class="hljs-attr">error</span>: error ? error.stack : <span class="hljs-literal">null</span>,
  };

  <span class="hljs-comment">// Send errorData to a logging service (e.g., via an HTTP request)</span>

  <span class="hljs-comment">// Return true to prevent the default browser error handling</span>
  <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
};
</code></pre>
<p>Keep in mind that the use of <code>window.onerror</code> has some limitations, and it may not capture all types of errors, such as syntax errors or errors in asynchronous code. </p>
<p>For a more comprehensive error handling solution, consider using tools like <code>try...catch</code> blocks, error boundary components in React, or specialized error tracking services.</p>
<h3 id="heading-2-unhandled-promise-rejections">2. <strong>Unhandled Promise Rejections:</strong></h3>
<p>When working with asynchronous code, particularly with promises in JavaScript, it's essential to handle errors to prevent unhandled promise rejections. </p>
<p>Unhandled promise rejections occur when a promise is rejected, but there is no corresponding <code>.catch()</code> or <code>await</code> to handle the rejection. This can lead to unexpected behavior and can make it challenging to debug issues in your application.</p>
<p>To implement global error handling for unhandled promise rejections, you can use the <code>unhandledrejection</code> event. This event is triggered whenever a promise is rejected, but there is no associated rejection handler.</p>
<p>Here's an example of how you can set up global error handling for unhandled promise rejections:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Setup global error handling for Unhandled Promise Rejections</span>
process.on(<span class="hljs-string">'unhandledRejection'</span>, <span class="hljs-function">(<span class="hljs-params">reason, promise</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Unhandled Rejection at:'</span>, promise, <span class="hljs-string">'reason:'</span>, reason);
  <span class="hljs-comment">// Additional logging or error handling can be added here</span>
});

<span class="hljs-comment">// Example of a Promise that is not handled</span>
<span class="hljs-keyword">const</span> unhandledPromise = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  reject(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'This Promise is not handled'</span>));
});

<span class="hljs-comment">// Uncomment the line below to see the global error handling in action</span>
<span class="hljs-comment">// unhandledPromise.then(result =&gt; console.log(result));</span>

<span class="hljs-comment">// Example of a Promise with proper error handling</span>
<span class="hljs-keyword">const</span> handledPromise = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  reject(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'This Promise is handled'</span>));
});

handledPromise
  .then(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(result))
  .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error:'</span>, error));
</code></pre>
<p>In this example:</p>
<p>The <code>unhandledRejection</code> event is registered on the <code>process</code> object. This event will be triggered whenever a promise is rejected without a corresponding rejection handler.</p>
<p>An example of an unhandled promise (<code>unhandledPromise</code>) is created. Uncommenting the line that uses this promise without a <code>.catch()</code> will trigger the <code>unhandledRejection</code> event.</p>
<p>An example of a properly handled promise (<code>handledPromise</code>) is created, and it includes a <code>.catch()</code> to handle any rejection.</p>
<p>When a promise is rejected without being handled, the <code>unhandledRejection</code> event is triggered, and it logs information about the rejected promise, such as the promise itself and the reason for rejection.</p>
<p>This approach allows you to catch unhandled promise rejections globally in your application, making it easier to identify and address issues related to asynchronous code. Always remember to include proper error handling for promises to ensure a robust and reliable application.</p>
<h2 id="heading-how-to-communicate-errors-to-users">How to Communicate Errors to Users</h2>
<h3 id="heading-1-user-friendly-error-messages">1. <strong>User-Friendly Error Messages:</strong></h3>
<p>When an error occurs, it's essential to communicate the issue to the user in a way that is easy to understand. Instead of displaying technical details, provide a simple and clear message.</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ErrorComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Oops! Something went wrong. Please try again later.<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;
}
</code></pre>
<h3 id="heading-2-error-boundaries">2. <strong>Error Boundaries:</strong></h3>
<p>React's error boundaries are components that catch JavaScript errors anywhere in their child component tree. They enable you to handle errors gracefully and display a fallback UI to users.</p>
<pre><code class="lang-jsx"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ErrorBoundary</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
  <span class="hljs-keyword">constructor</span>(props) {
    <span class="hljs-built_in">super</span>(props);
    <span class="hljs-built_in">this</span>.state = { <span class="hljs-attr">hasError</span>: <span class="hljs-literal">false</span> };
  }

  componentDidCatch(error, errorInfo) {
    logErrorToService(error, errorInfo);
    <span class="hljs-built_in">this</span>.setState({ <span class="hljs-attr">hasError</span>: <span class="hljs-literal">true</span> });
  }

  render() {
    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.state.hasError) {
      <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ErrorComponent</span> /&gt;</span></span>;
    }
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.props.children;
  }
}
</code></pre>
<p>Wrap components that might throw errors with the <code>ErrorBoundary</code> component to gracefully handle errors.</p>
<pre><code class="lang-jsx">&lt;ErrorBoundary&gt;
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">MyComponent</span> /&gt;</span></span>
&lt;/ErrorBoundary&gt;
</code></pre>
<h2 id="heading-how-to-handle-asynchronous-errors">How to Handle Asynchronous Errors</h2>
<h3 id="heading-1-try-catch-with-asyncawait">1. <strong>Try-Catch with Async/Await:</strong></h3>
<p>When working with asynchronous code, using <code>try</code> and <code>catch</code> blocks with <code>async/await</code> can help handle errors more effectively.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchData</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://api.example.com/data'</span>);
    <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> response.json();
    <span class="hljs-keyword">return</span> data;
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error fetching data:'</span>, error);
    <span class="hljs-keyword">throw</span> error; <span class="hljs-comment">// Re-throw the error to propagate it further</span>
  }
}
</code></pre>
<h3 id="heading-2-promisecatch">2. <strong>Promise.catch():</strong></h3>
<p>When dealing with promises, using the <code>.catch()</code> method allows you to handle errors in a concise manner.</p>
<pre><code class="lang-jsx">fetch(<span class="hljs-string">'https://api.example.com/data'</span>)
  .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> response.json())
  .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
    <span class="hljs-comment">// Process the data</span>
  })
  .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error fetching data:'</span>, error);
    <span class="hljs-comment">// Display a user-friendly error message</span>
    alert(<span class="hljs-string">'An error occurred while fetching data.'</span>);
  });
</code></pre>
<h2 id="heading-how-to-log-errors-for-debugging">How to Log Errors for Debugging</h2>
<p>Logging errors is crucial for debugging and improving the stability of your React application. Use browser developer tools or external logging services to capture and analyze errors.</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">logErrorToService</span>(<span class="hljs-params">error, errorInfo</span>) </span>{
  <span class="hljs-comment">// Send the error to a logging service (e.g., Sentry, Loggly)</span>
  <span class="hljs-comment">// Include additional information like errorInfo for better debugging</span>
  <span class="hljs-comment">// loggingService.logError(error, errorInfo);</span>
  <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Logged error:'</span>, error, errorInfo);
}
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In conclusion, effective error handling in React applications involves a combination of preventive measures, global error handling, user-friendly communication, and proper debugging practices. </p>
<p>By understanding different types of errors and implementing appropriate strategies, you can enhance the reliability and user experience of your React applications. </p>
<p>Remember, simplicity in error messages and clear communication with users go a long way in building trust and satisfaction. Always prioritize user experience when handling errors in your React projects. And make sure you stay updated with the latest React features and best practices to ensure the resilience and stability of your applications.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Exception Filters to Catch Bugs in Nest.js ]]>
                </title>
                <description>
                    <![CDATA[ It's common to find errors and bugs in your code if you're a software developer. They might occur because of incorrect input, from passing the wrong data types, or because of delays or response timeouts.  And even though errors and bugs are a part of... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/exception-filters-in-nestjs/</link>
                <guid isPermaLink="false">66bb51f1b0a396d22e4116f7</guid>
                
                    <category>
                        <![CDATA[ debugging ]]>
                    </category>
                
                    <category>
                        <![CDATA[ error handling ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ nestjs ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Okoye Chukwuebuka Victor ]]>
                </dc:creator>
                <pubDate>Fri, 23 Jun 2023 21:38:23 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/06/brett-jordan-XWar9MbNGUY-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>It's common to find errors and bugs in your code if you're a software developer. They might occur because of incorrect input, from passing the wrong data types, or because of delays or response timeouts. </p>
<p>And even though errors and bugs are a part of life, they can stress you out and decrease your productivity. Fortunately, you can limit the number of pests in your code by taking proactive measures to prevent and fix them. </p>
<p>In this article, you will learn how best to utilize exception filters to limit disruptions in your code implementations.</p>
<h2 id="heading-what-are-exception-filters">What Are Exception Filters?</h2>
<p>Exception filters are constructs of a programming language that help you handle exceptions or errors found in services or controller classes. Using these filters improves the efficiency of your codebase and makes errors more traceable, which helps you resolve them.</p>
<h3 id="heading-what-are-exception-filters-in-nestjs">What are Exception Filters in Nest.js?</h3>
<p>Nest.js has an inbuilt exception filter interface that you import from the <code>@nestjs/common package</code>. This interface gives you precise information about exceptions you may encounter so that you can know how to fix them. </p>
<p>Some built-in exception filters include <code>NotFoundException</code>, <code>UnauthorizedException</code>, and <code>RequestTimeOutException</code>, among others.</p>
<h2 id="heading-how-to-create-a-custom-exception-filter">How to Create a Custom Exception Filter</h2>
<p>To create a custom exception filter class, you define it with a <code>@Catch</code> decorator that takes in the type of exception the filter should catch. This class then implements the <code>ExceptionFilter</code> interface. This way you will have access to the <code>catch</code> method that the interface provides. </p>
<p>NestJS allows you to create your own exception filters so you can define what sort of information it should return.</p>
<pre><code class="lang-typescript"><span class="hljs-meta">@Catch</span>(HttpException)
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> TestExceptionFilter <span class="hljs-keyword">implements</span> ExceptionFilter {
  <span class="hljs-keyword">catch</span>(exception: HttpException, host: ArgumentsHost) {
    <span class="hljs-keyword">const</span> ctx = host.switchToHttp();
    <span class="hljs-keyword">const</span> response = ctx.getResponse&lt;Response&gt;();
    <span class="hljs-keyword">const</span> request = ctx.getRequest&lt;Request&gt;();
    <span class="hljs-keyword">const</span> status = exception.getStatus();

    response
      .status(status)
      .json({
        statusCode: status,
        timestamp: <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().toISOString(),
        path: request.url,
      });
  }
}
</code></pre>
<p>As you can see above, the catch method takes in two argument inputs: the <code>exception:HttpException</code> and the <code>host:argumentsHost</code>. </p>
<p><code>HttpException</code> is the exception thrown when an <code>HTTP</code> request fails and returns the appropriate Error Message with a status code as a response to the client. </p>
<p>The <code>argumentsHost</code> parameter provides information about the current request and response cycle. Here the code extracts the Response and Request objects from the <code>ArgumentsHost</code> object using the <code>switchToHttp</code> method. It then calls the <code>getStatus</code> method from the <code>HttpException</code> object in order to retrieve the <code>HTTP</code> status code of the error.</p>
<p> A <code>JSON</code> object gets returned. It contains the status code, the error timestamp, and the request URL, setting the <code>HTTP</code> response status code to be the error status code.</p>
<p>Another exciting thing to note is that you can modify the status code and error message of existing exception filters like <code>NotFoundException</code> so that they display your own custom error message and status code. Here is an illustration below:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> NotFoundException <span class="hljs-keyword">extends</span> HttpException {
  <span class="hljs-keyword">constructor</span>(<span class="hljs-params">message: <span class="hljs-built_in">string</span></span>) {
    <span class="hljs-built_in">super</span>(message || <span class="hljs-string">'Not Found'</span>, HttpStatus.NOT_FOUND);
  }
}
</code></pre>
<p>The example above shows that the <code>NotFoundException</code> class was modified to accept a <code>message</code> parameter in the constructor method or give a default value of 'Not Found'. </p>
<p>By doing this you are now able to customize an error message for your <code>NotFoundException</code> class and return a <code>404</code> status code.</p>
<h2 id="heading-how-to-bind-exception-filters-in-nestjs">How to Bind Exception Filters in Nest.js</h2>
<p>You might be wondering how you can implement the custom or modified exception you've created for your application. Well, you use something called <strong>binding</strong>. </p>
<p>There are several ways in which you can bind exception filters to your application. Here are three major ways you can do it:</p>
<ol>
<li>Global Scope</li>
<li>Controller Scope</li>
<li>Method Scope</li>
</ol>
<h3 id="heading-binding-using-global-scope"><strong>Binding using Global Scope</strong></h3>
<p>Just like the name “Global” implies, it covers the entirety of a thing – in this case the application. The custom exception filter is <strong>bonded</strong> to the entirety of your web application by using the <code>useGlobalFilters()</code> function. An instance of your custom exception filter gets passed in before starting up the server. </p>
<p>Here is an example of what that looks like:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">bootstrap</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> app = <span class="hljs-keyword">await</span> NestFactory.create(AppModule);
  app.useGlobalFilters(<span class="hljs-keyword">new</span> TestExceptionFilter());
  <span class="hljs-keyword">await</span> app.listen(<span class="hljs-number">3000</span>);
}
bootstrap();
</code></pre>
<p>If you bind the exception filter to the global scope, it means that any exceptions of type <code>HttpException</code> thrown from any controller or method within the application will be handled by the <code>TestExceptionFilter</code>.</p>
<h3 id="heading-binding-using-controller-scope"><strong>Binding using Controller Scope</strong></h3>
<p>If you want to handle an exception that not only covers the specific methods in your application but also the entire controller with the methods in it, you can the <code>@UseFilters</code> to bind the custom exception to the controller. Check out the below is example:</p>
<pre><code class="lang-typescript"><span class="hljs-meta">@UseFilters</span>(TestExceptionFilter)
<span class="hljs-meta">@Controller</span>(<span class="hljs-string">'users'</span>)
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> UsersController {
  <span class="hljs-meta">@Get</span>()
  <span class="hljs-keyword">async</span> findUsers() {
    <span class="hljs-comment">// ...</span>
  }
}
</code></pre>
<p>In this example, the custom exception filter is bonded to the controller by putting it ahead of the <code>@Controller</code> decorator. This way it handles any error that comes from the routes in this controller.</p>
<h3 id="heading-binding-using-method-scope"><strong>Binding using Method Scope</strong></h3>
<p>In this form of binding, you make use of the <code>@UseFilters</code> decorator to apply the Custom ExceptionFilter you defined to a method in your application. Here is an example:</p>
<pre><code class="lang-typescript"><span class="hljs-meta">@Controller</span>()
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> UsersController {
  <span class="hljs-meta">@Get</span>()
  <span class="hljs-meta">@UseFilters</span>(TestExceptionFilter)
  <span class="hljs-keyword">async</span> findUsers() {
    <span class="hljs-comment">// ...</span>
  }
}
</code></pre>
<p>In this example, you're using the <code>@UseFilters</code> decorator to bind the <code>TestExceptionFilter</code> exception filter to the <code>findUsers</code> method. This means that if any exception occurs within the <code>findUsers()</code> method, the <code>TestExceptionFilter</code> will catch and handle it.</p>
<h2 id="heading-debugging-made-easier">Debugging Made Easier</h2>
<p>In this tutorial, you learned about exception filters in Nest.js, and how to create custom exception filters. You also saw some different ways in which you can implement them in your applications.</p>
<p>All the methods discussed are good ways to handle exceptions. By implementing these techniques, you can ensure smoother application performance and provide a better user experience.</p>
<p>If you enjoyed reading this article, you can share and follow me on <a target="_blank" href="https://twitter.com/okoyevictorr">Twitter</a> and <a target="_blank" href="https://www.linkedin.com/in/officalrajdeepsingh/">Linkedin</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Python Print Exception – How to Try-Except-Print an Error ]]>
                </title>
                <description>
                    <![CDATA[ Every programming language has its way of handling exceptions and errors, and Python is no exception.  Python comes with a built-in try…except syntax with which you can handle errors and stop them from interrupting the running of your program. In thi... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/python-print-exception-how-to-try-except-print-an-error/</link>
                <guid isPermaLink="false">66adf1e16992d2a84c5d793c</guid>
                
                    <category>
                        <![CDATA[ error handling ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kolade Chris ]]>
                </dc:creator>
                <pubDate>Wed, 15 Mar 2023 21:31:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/03/pythonExceptionHandling.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Every programming language has its way of handling exceptions and errors, and Python is no exception. </p>
<p>Python comes with a built-in <code>try…except</code> syntax with which you can handle errors and stop them from interrupting the running of your program.</p>
<p>In this article, you’ll learn how to use that <code>try…except</code> syntax to handle exceptions in your code so they don’t stop your program from running.</p>
<h2 id="heading-what-well-cover">What We'll Cover</h2>
<ul>
<li><a class="post-section-overview" href="#heading-what-is-an-exception">What is an Exception?</a></li>
<li><a class="post-section-overview" href="#heading-the-tryexcept-syntax">The <code>try…except</code> Syntax</a></li>
<li><a class="post-section-overview" href="#heading-how-to-handle-exceptions-with-tryexcept">How to Handle Exceptions with <code>try…except</code></a></li>
<li><a class="post-section-overview" href="#heading-how-to-print-an-exception-with-tryexcept">How to Print an Exception with <code>try…except</code></a></li>
<li><a class="post-section-overview" href="#heading-how-to-print-the-exception-name">How to Print the Exception Name</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-what-is-an-exception">What is an Exception?</h2>
<p>In Python, an exception is an error object. It is an error that occurs during the execution of your program and stops it from running – subsequently displaying an error message.</p>
<p>When an exception occurs, Python creates an exception object which contains the type of the error and the line it affects.</p>
<p>Python has many built-in exceptions such as <code>IndexError</code>, <code>NameError</code>, <code>TypeError</code>, <code>ValueError</code>, <code>ZeroDivisionError</code> <code>KeyError</code>, and many more. </p>
<h2 id="heading-the-tryexcept-syntax">The <code>try…except</code> Syntax</h2>
<p>Instead of allowing these exceptions to stop your program from running, you can put the code you want to run in a <code>try</code> block and handle the exception in the <code>except</code> block.</p>
<p>The basic syntax of <code>try…except</code> looks like this:</p>
<pre><code class="lang-py"><span class="hljs-keyword">try</span>:
  <span class="hljs-comment"># code to run</span>
<span class="hljs-keyword">except</span>:
  <span class="hljs-comment"># handle error</span>
</code></pre>
<h2 id="heading-how-to-handle-exceptions-with-tryexcept">How to Handle Exceptions with <code>try…except</code></h2>
<p>You can handle each of the exceptions mentioned in this article with <code>try…except</code>. In fact, you can handle all the exceptions in Python with <code>try…except</code>.</p>
<p>For example, if you have a large program and you don’t know whether an identifier exists or not, you can execute what you want to do with the identifier in a <code>try</code> block and handle a possible error in the <code>except</code> block:</p>
<pre><code class="lang-py"><span class="hljs-keyword">try</span>:
  print(<span class="hljs-string">"Here's variable x:"</span>, x)
<span class="hljs-keyword">except</span>:
  print(<span class="hljs-string">"An error occured"</span>) <span class="hljs-comment"># An error occured</span>
</code></pre>
<p>You can see that the <code>except</code> ran because there’s no variable called <code>x</code> in the code.</p>
<p>Keep reading. Because I will show you how to make those errors look better by showing you how to handle exceptions gracefully.</p>
<h2 id="heading-how-to-print-an-exception-with-tryexcept">How to Print an Exception with <code>try…except</code></h2>
<p>But what if you want to print the exact exception that occurred? You can do this by assigning the <code>Exception</code> to a variable right in front of the <code>except</code> keyword.</p>
<p>When you do this and print the Exception to the terminal, it is the value of the <code>Exception</code> that you get.</p>
<p>This is how I printed the <code>ZeroDivisionError</code> exception to the terminal:</p>
<pre><code class="lang-py"><span class="hljs-keyword">try</span>:
    res = <span class="hljs-number">190</span> / <span class="hljs-number">0</span>
<span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> error:
    <span class="hljs-comment"># handle the exception</span>
    print(<span class="hljs-string">"An exception occurred:"</span>, error) <span class="hljs-comment"># An exception occurred: division by zero</span>
</code></pre>
<p>And this is how I printed the <code>NameError</code> exception too:</p>
<pre><code class="lang-py"><span class="hljs-keyword">try</span>:
  print(<span class="hljs-string">"Here's variable x:"</span>, x)
<span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> error:
  print(<span class="hljs-string">"An error occurred:"</span>, error) <span class="hljs-comment"># An error occurred: name 'x' is not defined</span>
</code></pre>
<p>You can follow this pattern to print any exception to the terminal.</p>
<h2 id="heading-how-to-print-the-exception-name">How to Print the Exception Name</h2>
<p>What if you want to get the exact exception name and print it to the terminal? That’s possible too. All you need to do is use the <code>type()</code> function to get the type of the exception and then use the <code>__name__</code> attribute to get the name of the exception.</p>
<p>This is how I modified the <code>ZeroDivisionError</code> example to print the exact exception:</p>
<pre><code class="lang-py"><span class="hljs-keyword">try</span>:
    res = <span class="hljs-number">190</span> / <span class="hljs-number">0</span>
<span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> error:
    <span class="hljs-comment"># handle the exception</span>
    print(<span class="hljs-string">"An exception occurred:"</span>, type(error).__name__) <span class="hljs-comment"># An exception occurred: ZeroDivisionError</span>
</code></pre>
<p>And this is how I modified the other example to print the <code>NameError</code> example:</p>
<pre><code class="lang-py"><span class="hljs-keyword">try</span>:
  print(<span class="hljs-string">"Here's variable x:"</span>, x)
<span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> error:
  print(<span class="hljs-string">"An error occurred:"</span>, type(error).__name__) <span class="hljs-comment"># An error occurred: NameError</span>
</code></pre>
<p>Normally, when you encounter an Exception such as <code>NameError</code> and <code>ZeroDivisionError</code>, for example, you get the error in the terminal this way:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/Screenshot-2023-03-13-at-17.58.33.png" alt="Screenshot-2023-03-13-at-17.58.33" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/Screenshot-2023-03-13-at-17.58.54.png" alt="Screenshot-2023-03-13-at-17.58.54" width="600" height="400" loading="lazy"> </p>
<p>You can combine the <code>type()</code> function and that error variable to make the exception look better:</p>
<pre><code class="lang-py"><span class="hljs-keyword">try</span>:
  print(<span class="hljs-string">"Here's variable x:"</span>, x)
<span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> error:
  print(<span class="hljs-string">"An error occurred:"</span>, type(error).__name__, <span class="hljs-string">"–"</span>, error) <span class="hljs-comment"># An error occurred: NameError – name 'x' is not defined</span>
</code></pre>
<pre><code class="lang-py"><span class="hljs-keyword">try</span>:
    res = <span class="hljs-number">190</span> / <span class="hljs-number">0</span>
<span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> error:
    <span class="hljs-comment"># handle the exception</span>
    print(<span class="hljs-string">"An exception occurred:"</span>, type(error).__name__, <span class="hljs-string">"–"</span>, error) <span class="hljs-comment"># An exception occurred: ZeroDivisionError – division by zero</span>
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>As shown in this article, the <code>try…except</code> syntax is a great way to handle errors and prevent your program from stopping during execution.</p>
<p>You can even print that <code>Exception</code> to the terminal by assigning the error to a variable, and get the exact type of the <code>Exception</code> with the <code>type()</code> function.</p>
<p>Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Common Errors in Python and How to Fix Them ]]>
                </title>
                <description>
                    <![CDATA[ Python is a popular programming language that is easy to learn and use. But like any programming language, Python is prone to errors. In this tutorial, we'll cover some of the most common errors in Python and how to fix them. Syntax Errors in Python ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/common-errors-in-python-and-how-to-fix-them/</link>
                <guid isPermaLink="false">66d46091f855545810e934bd</guid>
                
                    <category>
                        <![CDATA[ error ]]>
                    </category>
                
                    <category>
                        <![CDATA[ error handling ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Jeremiah Oluseye ]]>
                </dc:creator>
                <pubDate>Mon, 13 Mar 2023 19:07:43 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/03/errors.JPG" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Python is a popular programming language that is easy to learn and use. But like any programming language, Python is prone to errors.</p>
<p>In this tutorial, we'll cover some of the most common errors in Python and how to fix them.</p>
<h2 id="heading-syntax-errors-in-python">Syntax Errors in Python</h2>
<p>Syntax errors occur when you have a typo or other mistake in your code that causes it to be invalid syntax. These errors are usually caught by Python's interpreter when you try to run the code.</p>
<p>Here are some tips for avoiding syntax errors:</p>
<ul>
<li><p>Double-check your code for typos or other mistakes before running it.</p>
</li>
<li><p>Use a code editor that supports syntax highlighting to help you catch syntax errors.</p>
</li>
<li><p>Read the error message carefully to determine the location of the error.</p>
</li>
</ul>
<p>Example:</p>
<pre><code class="lang-python"><span class="hljs-keyword">if</span> x = <span class="hljs-number">10</span>:
    print(<span class="hljs-string">"x is equal to 10"</span>)
</code></pre>
<p>In this example, we are trying to assign the value 10 to the variable x using the assignment operator (=) inside an if statement.</p>
<p>But the correct syntax for comparing values in an if statement is to use the comparison operator (==).</p>
<p>So here's how you fix this one:</p>
<pre><code class="lang-python"><span class="hljs-keyword">if</span> x == <span class="hljs-number">10</span>:
    print(<span class="hljs-string">"x is equal to 10"</span>)
</code></pre>
<h2 id="heading-indentation-errors-in-python">Indentation Errors in Python</h2>
<p>One of the most common errors in Python is indentation errors. Unlike many other programming languages, Python uses whitespace to indicate blocks of code, so proper indentation is critical.</p>
<p>Here are a few rules to keep in mind when it comes to indentation in Python:</p>
<ul>
<li><p>Use four spaces for each level of indentation.</p>
</li>
<li><p>Don't mix tabs and spaces for indentation.</p>
</li>
<li><p>Make sure your indentation is consistent throughout your code.</p>
</li>
</ul>
<p>To avoid indentation errors, it's a good idea to use a code editor that supports automatic indentation, such as PyCharm or Visual Studio Code.</p>
<p>Example:</p>
<pre><code class="lang-python"><span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>):
print(i)
</code></pre>
<p>In this example, the code inside the for loop is not indented correctly.</p>
<p>Fix:</p>
<pre><code class="lang-python"><span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>):
    print(i)
</code></pre>
<h2 id="heading-name-errors-in-python">Name Errors in Python</h2>
<p>Name errors occur when you try to use a variable or function that hasn't been defined. For example, if you try to print the value of a variable that hasn't been assigned a value yet, you'll get a name error.</p>
<p>Here are some tips for avoiding name errors:</p>
<ul>
<li><p>Make sure you've defined all variables and functions before using them.</p>
</li>
<li><p>Double-check the spelling and capitalization of your variable and function names.</p>
</li>
<li><p>Use Python's built-in debugging tools, such as <code>print</code> statements, to help you track down name errors.</p>
</li>
</ul>
<p>Example:</p>
<pre><code class="lang-python">my_variable = <span class="hljs-number">5</span>
print(my_vairable)
</code></pre>
<p>In this example, we misspelled the variable name my_variable as my_vairable.</p>
<p>Fix:</p>
<pre><code class="lang-python">my_variable = <span class="hljs-number">5</span>
print(my_variable)
</code></pre>
<h2 id="heading-type-errors-in-python">Type Errors in Python</h2>
<p>Another common error in Python is type errors. Type errors occur when you try to perform an operation on data of the wrong type. For example, you might try to add a string and a number, or you might try to access an attribute of an object that doesn't exist.</p>
<p>Here are some tips for avoiding type errors:</p>
<ul>
<li><p>Use type annotations in your code to make it clear what types of data you expect.</p>
</li>
<li><p>Use Python's built-in type-checking tools, such as the <code>typing</code> module and the <code>mypy</code> tool.</p>
</li>
<li><p>Write unit tests to ensure that your code handles different types of data correctly.</p>
</li>
</ul>
<p>Example:</p>
<pre><code class="lang-python">x = <span class="hljs-string">"5"</span>
y = <span class="hljs-number">10</span>
result = x + y
</code></pre>
<p>In this example, we are trying to concatenate a string and an integer, which is not possible.</p>
<p>Fix:</p>
<pre><code class="lang-python">x = <span class="hljs-string">"5"</span>
y = <span class="hljs-number">10</span>
result = int(x) + y
</code></pre>
<p>Here, we convert the string to an integer using the int() function before performing the addition.</p>
<h2 id="heading-index-errors-in-python">Index Errors in Python</h2>
<p>Index errors occur when you try to access an item in a list or other sequence using an index that is out of range. For example, if you try to access the fifth item in a list that only has four items, you'll get an index error.</p>
<p>Here are some tips for avoiding index errors:</p>
<ul>
<li><p>Make sure you're using the correct index values for your sequence.</p>
</li>
<li><p>Use Python's built-in functions, such as <code>len</code>, to determine the length of your sequence before trying to access items in it.</p>
</li>
<li><p>Use exception handling, such as <code>try</code> and <code>except</code> blocks, to handle index errors gracefully.</p>
</li>
</ul>
<p>Example:</p>
<pre><code class="lang-python">my_list = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]
print(my_list[<span class="hljs-number">5</span>])
</code></pre>
<p>In this example, we are trying to access an item at index 5, which is outside the range of the list.</p>
<p>Fix:</p>
<pre><code class="lang-python">my_list = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]
print(my_list[<span class="hljs-number">3</span>])
</code></pre>
<p>Here, we access the item at index 3, which is within the range of the list.</p>
<h2 id="heading-key-errors-in-python">Key Errors in Python</h2>
<p>Key errors occur when you try to access a dictionary using a key that doesn't exist. For example, if you try to access the value associated with a key that hasn't been defined in a dictionary, you'll get a key error.</p>
<p>Here are some tips for avoiding key errors:</p>
<ul>
<li><p>Make sure you're using the correct keys for your dictionary.</p>
</li>
<li><p>Use Python's built-in <code>in</code> operator to check whether a key exists in a dictionary before trying to access it.</p>
</li>
<li><p>Use exception handling, such as <code>try</code> and <code>except</code> blocks, to handle key errors gracefully.</p>
</li>
</ul>
<p>Example:</p>
<pre><code class="lang-python">my_dict = {<span class="hljs-string">"name"</span>: <span class="hljs-string">"John"</span>, <span class="hljs-string">"age"</span>: <span class="hljs-number">25</span>}
print(my_dict[<span class="hljs-string">"gender"</span>])
</code></pre>
<p>In this example, we are trying to access the value for the key "gender", which does not exist in the dictionary.</p>
<p>Fix:</p>
<pre><code class="lang-python">my_dict = {<span class="hljs-string">"name"</span>: <span class="hljs-string">"John"</span>, <span class="hljs-string">"age"</span>: <span class="hljs-number">25</span>}
print(my_dict.get(<span class="hljs-string">"gender"</span>, <span class="hljs-string">"Key not found"</span>))
</code></pre>
<p>Here, we use the <code>get()</code> method to access the value for the key "gender". The second argument of the <code>get()</code> method specifies the default value to return if the key does not exist.</p>
<h2 id="heading-attribute-errors-in-python">Attribute Errors in Python</h2>
<p>Attribute errors occur when you try to access an attribute of an object that doesn't exist, or when you try to access an attribute in the wrong way.</p>
<p>There are several different types of attributes in Python:</p>
<ul>
<li><p>Instance attributes: These are attributes that belong to a specific instance of a class.</p>
</li>
<li><p>Class attributes: These are attributes that belong to a class rather than an instance.</p>
</li>
<li><p>Static attributes: These are attributes that belong to a class, but can be accessed without creating an instance of the class.</p>
</li>
</ul>
<p>To avoid attribute errors, it's important to understand the different types of attributes and how they work. You should also make sure that you're accessing attributes in the correct way, and that you're not trying to access attributes that don't exist.</p>
<p>Example:</p>
<pre><code class="lang-python">my_list = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]
my_list.append(<span class="hljs-number">5</span>)
my_list.add(<span class="hljs-number">6</span>)
</code></pre>
<p>In this example, we are trying to add an item to the list using the <code>add()</code> method, which does not exist for lists.</p>
<p>Fix:</p>
<pre><code class="lang-python">my_list = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]
my_list.append(<span class="hljs-number">5</span>)
</code></pre>
<p>Here, we use the <code>append()</code> method to add an item to the list.</p>
<h2 id="heading-general-tips">General Tips</h2>
<p>Here are a few general tips for avoiding common errors in Python:</p>
<ul>
<li><p>Use good coding practices, such as commenting your code and following the DRY (Don't Repeat Yourself) principle.</p>
</li>
<li><p>Write unit tests to catch errors before they make it into your production code.</p>
</li>
<li><p>Read the documentation for the modules and functions you're using to make sure you're using them correctly.</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Python is a powerful language with many features, but like any programming language, it can be prone to errors.</p>
<p>In this article, we covered some of the most common errors in Python and how to fix them. By understanding these errors and how to fix them, you can become a more confident and effective Python programmer.</p>
<p>Let’s connect on <a target="_blank" href="https://twitter.com/Olujerry19">Twitter</a> and <a target="_blank" href="https://www.linkedin.com/in/jeremiah-oluseye-58457719a/">LinkedIn</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Debug Errors in Your Source Code ]]>
                </title>
                <description>
                    <![CDATA[ The process of handling errors is known as debugging. It involves identifying and removing errors from your program.  If you want to be an efficient programmer, you'll want to cultivate your ability to debug code. It's one of the main skills you'll n... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-debug-errors-in-your-source-code/</link>
                <guid isPermaLink="false">66c71fd9be8746551a50b625</guid>
                
                    <category>
                        <![CDATA[ debugging ]]>
                    </category>
                
                    <category>
                        <![CDATA[ error handling ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Mabel Obadoni ]]>
                </dc:creator>
                <pubDate>Fri, 24 Feb 2023 23:37:18 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/02/Errors.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The process of handling errors is known as debugging. It involves identifying and removing errors from your program. </p>
<p>If you want to be an efficient programmer, you'll want to cultivate your ability to debug code. It's one of the main skills you'll need as a software developer or programmer. This means you need to learn all about errors, too. 🤷</p>
<p>Errors can come in many forms – from as little as an omission of a semicolon to as huge as a crashed database. They're all part of the bittersweet experience of programming.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/image-126.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Regardless of your stage in programming, you most likely will come across at least one type of error while coding. The error could come up during writing code, running it, or even testing it. And there's usually a specific remedy to each error. This implies that not all errors are handled or solved the same way.</p>
<p>Errors in programming are also referred to as bugs. These bugs prevent your program from doing what it's instructed. Once you have a grasp of common errors, you'll be able to figure out the right treatment for the error you're experiencing. </p>
<p>To debug errors in your source code, you'll need to understand:</p>
<ul>
<li>The sources of the errors in your code – What exactly is the cause of the errors displaying?</li>
<li>The types of errors –Now that I have an error, what type is it? What should I do to clear these red lines off my screen?</li>
</ul>
<p>This article will focus on how to answer these questions.</p>
<h2 id="heading-where-do-errors-come-from-in-coding"><strong>Where Do Errors Come From in Coding?</strong></h2>
<p>The first step in finding a solution is knowing exactly the source of the problem. This will guide you in suggesting or building a solution. When writing your code in whatever programming language you use, errors can occur due to different factors.</p>
<p>The main sources of error include:</p>
<h3 id="heading-human-errors">Human Errors</h3>
<p>Even though Artificial Intelligence plays a larger and larger role in many operations, the fact remains that humans still write source code. </p>
<p>Errors caused by omission, knowledge gaps, or the lack of proper structure come from the developer. </p>
<p>When a developer lacks the technical knowledge of the syntax of a particular language, there's bound to be errors in the source code. Or if they mean one thing and write another in code, the conflict in logic will always result in an error.</p>
<p>So, before you venture into coding in any language, make sure you understand the structure behind it and the rules that govern its programs. This will help you write fewer errors into your code that you then have to debug.</p>
<h3 id="heading-machine-errors">Machine Errors</h3>
<p>For issues such as low memory, little storage space, and slow CPU processing speed, the machine also plays a role in causing errors. In fact a machine with a slow memory can cause runtime errors (errors due to slow code execution).</p>
<p>When getting a computer, if you're able, make sure to get one that matches up to the tasks you'll send its way. You should also use cloud storage and other cloud operations to reduce the risks of errors caused by your machine.</p>
<h3 id="heading-procedural-errors">Procedural Errors</h3>
<p>Solving a problem requires following certain methods. Programming has its underlying methodology which you should follow whenever possible. </p>
<p>This is why standard bodies exist, such as the World Wide Web consortium. It ensures that certain standards are followed when developing programs. </p>
<p>Errors can occur when you ignore the standard methods entirely and try to maneuver your own way. Such code may not go beyond your machine as it may not be production worthy.</p>
<p>Study the procedures for building and operating the solution you are coding and try to follow them.</p>
<h2 id="heading-types-of-coding-errors"><strong>Types of Coding Errors</strong></h2>
<p>Errors can occur regardless of your skill in programming. Your coding prowess is displayed when you can confidently decipher the error message and figure out what type of error occurred. </p>
<p>Many programming languages have similar structures, especially Object Oriented Programming languages (such as Python and JavaScript). These similarities in structure means that they also have similar error patterns. </p>
<p>In programming, the most common errors are:</p>
<h3 id="heading-syntax-errors">Syntax Errors</h3>
<p>The word "syntax" simply means arrangement. In programming, syntax is the arrangement of the code following a set of rules or patterns. </p>
<p>Just like in the English language where the letters are arranged from A - Z, programming languages also have their syntax you'll need to follow so the program runs seamlessly. </p>
<p>When you're writing in English, for example, if you don't follow the grammar and syntax rules of the language, your words won't make a lot of sense. The same is true in programming: if you don't adhere to the syntax rules of the programming language, you'll get a <strong>Syntax Error.</strong></p>
<p>Therefore, a syntax error is that error caused by disobeying the rules guiding a particular language. And the error message that pops up prevents your program from running.</p>
<p>Syntax Errors can be caused by various factors such as incorrect spelling, omitted punctuation, wrong use of quotes (" "), incorrect declaration of variables and values, and more.</p>
<p>As small as these errors may seem, they can break your source code if not properly solved. When any of these syntax errors occur, your compiler responds in two ways:</p>
<ul>
<li><strong>It highlights the code line where the error has occurred:</strong> This will help you know the exact spot to check for your mistake.</li>
<li><strong>It gives at least</strong> a <strong>one sentence explanation of the error type</strong>.</li>
</ul>
<p>In most cases, the compiler will indicate that it is a "Syntax Error" and sometimes point to what was omitted, included, or misplaced. Here's an example:</p>
<pre><code class="lang-reactjs">// importing the required dependencies and components
import { BrowserRouter as Router, Route, Switch,Redirect } from 'react-router-dom';
import './App.css';
import Home from './components/Home';
import About from './components/About';
import Projects from './components/Projects';
import Contact from './components/Contact';
import Nav from './components/Nav';


function App() {
  return (
    &lt;div className='App'&gt;
      &lt;Router&gt;
        {/* &lt;Nav /&gt; */}
        &lt;Switch&gt;
          &lt;Route exact path='/'  component={Home}/&gt;
          &lt;Route  path='/About'  component={About} /&gt;
          &lt;Route path='/Projects' component={Projects} /&gt;
          &lt;Route path='/Contact'  component={Contact} /&gt;
          &lt;Redirect to ="/" /&gt;

        &lt;/Switch&gt;
      &lt;/Router&gt;  
    &lt;/div&gt;
</code></pre>
<p>The above snippet is from a React.js project. According to React syntax, if you declare a component you must use it, otherwise it'll throw a syntax error as seen in the screenshot below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/SC4.PNG" alt="Image" width="600" height="400" loading="lazy">
<em>Syntax error</em></p>
<p>In the example, the Nav component was declared in the set of import statements but it wasn't called in the routing statement. Because of this, it displays an error message in the terminal.</p>
<p>Beginners in programming often encounter syntax errors as they're learning – especially if you're juggling between two different languages at the same time. With consistent practice, you can get better at writing your source code that complies with the syntax rules of the language you're using. </p>
<h3 id="heading-logic-or-semantic-errors">Logic or Semantic Errors</h3>
<p>Another word for logic is reasoning. Writing source code for any program requires a lot of reasoning. Remember that coding is a means of providing solutions to problems. So your solution must follow the logic that guides it.</p>
<p>Also referred to as a semantic error, a logic error is an error that occurs when a program outputs something different from what was intended. Whenever your program behaves in a way that's different from what you outlined it to do, you have encountered a logical error.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/SC21-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> pandas <span class="hljs-keyword">as</span> pd
<span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
a = <span class="hljs-number">5</span>
b =<span class="hljs-string">"10"</span>
print(c=a+b)
</code></pre>
<p>In the above example, it is clear that the compiler couldn't add a string and a number because the number in the string was not implicitly converted to the <strong>int</strong> datatype. </p>
<p>You can also see that there is a syntax error in this program as well when you look at the <strong>print()</strong> statement. You can debug the logic error by converting the string to an integer datatype as show below:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> pandas <span class="hljs-keyword">as</span> pd
<span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
a = <span class="hljs-number">5</span>
b = Int(<span class="hljs-string">"10"</span>)
print(c=a+b)
</code></pre>
<p>Unlike a syntax error, a logic error may not prevent your program from running. Instead, it will run but display an incorrect output.</p>
<h3 id="heading-what-causes-logic-errors">What Causes Logic Errors?</h3>
<p><strong>Wrong Declaration of Data Type:</strong> Using the example above, the second variable is a string because of the quotes surrounding it. So, the compiler assumes that you want to place both variables side by side. So always make sure you're meticulous with your data type declaration and conversion.</p>
<p><strong>Incorrect sequence</strong>: Say you were to write, "Code love I to". Well, this sentence makes no logical sense because the words are not placed in the proper order. </p>
<p>The same goes for programming languages. When the code is not sequential, the compiler again assumes a meaning for your code and then gives you an output different from your expectations. </p>
<p>For instance, a function (in JavaScript) that is declared locally will be available globally due to the semantics of JavaScript function scope. So, if you'd need that particular function all through your source code, it is better to declare it in a global scope.</p>
<p>Scope in JS simply means the location of a declared variable and how it can be accessed. A variable has a global scope if it can be accessed anywhere along the entire source code. A local variable is one limited to only the block within which it is declared. The difference between a global variable and a local variable is the accessibility.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> age =prompt(<span class="hljs-string">"Enter your age"</span>)

 <span class="hljs-keyword">if</span> (age&lt;<span class="hljs-number">18</span>){
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"you are a minor"</span>)
 }
 <span class="hljs-keyword">else</span>{
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"You are"</span> + age + <span class="hljs-string">"years old"</span>)
 }
</code></pre>
<p>In the above code snippet, the variable "age" is globally declared that is why it can be called anywhere in the entire source code.</p>
<p>Incorrect Sequence is a logical error because variables must be rightly declared if they are to be used repeatedly. </p>
<p><strong>Misplaced Conditional Statement, Boolean or Logical Expressions:</strong> Logical expressions such as if-else, do-while, and the rest are the major causes of logical errors. When they're not properly placed, there's every tendency to get an incorrect output. Most programs rely a lot on logical expressions, so you need to know how to use them.</p>
<p>Logical errors can happen to anyone, regardless of skill level – just like all errors. So spend some time getting your logic right before you start coding. Some programmers go as far as drawing a schematic diagram to emphasize the logic they want for their program.</p>
<h3 id="heading-runtime-error">Runtime Error</h3>
<p>Every program has a certain amount of time it takes to execute. As a programmer, it is your duty to ensure that your program loads in the shortest possible time. </p>
<p>Remember, a slow program won't do well in the marketplace. Nobody wants an application that "wastes" their time, right?</p>
<p>Runtime, in simple terms, is the time taken for a program to execute or run. You can have your code syntax well written following a specified logic and still encounter errors as or when your program executes. This problem is caused by a runtime error.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/image-125.png" alt="APC Screen showing error alert" width="600" height="400" loading="lazy">
<em>A PC Screen showing error alert</em></p>
<p>As seen in the above picture, Runtime errors can occur while your program is being executed – the time between interpreting your codes and showing the required output.</p>
<p>These errors can be caused by a non-declared variable, a slow internet connection or many other reasons during the course of code execution.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> country = <span class="hljs-string">"Nigeria"</span>
<span class="hljs-keyword">let</span> indp = <span class="hljs-number">1960</span>
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Election</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">if</span> ( country == <span class="hljs-string">"Nigeria"</span>){
    <span class="hljs-built_in">console</span>.log ( country + <span class="hljs-string">"had her "</span>+ <span class="hljs-string">"independence in "</span> + indp)
    }
    }
election()
</code></pre>
<p>The above code will throw a runtime error because the function being called is different from the one declared.</p>
<h4 id="heading-how-to-solve-runtime-errors">How to solve runtime errors</h4>
<p>The best way to resolve runtime errors is to address them based on their cause. For a non-declared variable, ensure that the variable is properly declared using the right syntax and that the declared variable is the same as that which is called, as illustrated in the code block below:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> name = <span class="hljs-string">"Ayomide"</span>
<span class="hljs-built_in">console</span>.log (name + <span class="hljs-string">" "</span> +<span class="hljs-string">" was my colleague"</span>)
</code></pre>
<p>In the case of low memory, clear your cache and refresh your browser or restart your computer. </p>
<p>For poor internet connection, switch your internet service provider or close some opened tabs on your browser.</p>
<p>In severe cases, back up your source code and solve the hardware problem that your computer may be experiencing.</p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>Errors can occur in any program, no matter the skill of the programmer. What sets you apart is your ability to find and debug these errors.</p>
<p>The more errors you debug, the better you become at writing clean and performant code. Look out for the next error line and swing into action!  </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Type Error vs Reference Error in JavaScript – What's the Difference? ]]>
                </title>
                <description>
                    <![CDATA[ As a JavaScript developer, you've likely encountered different types of errors while coding. Most of the time these will be type errors or reference errors. But have you ever wondered what they mean? Have you ever tried reading about the error type s... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/type-error-vs-reference-error-javascript/</link>
                <guid isPermaLink="false">66ba2a4b4ae6042994edfa2e</guid>
                
                    <category>
                        <![CDATA[ error ]]>
                    </category>
                
                    <category>
                        <![CDATA[ error handling ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Tejan Singh ]]>
                </dc:creator>
                <pubDate>Wed, 15 Feb 2023 17:12:30 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/02/pexels-kim-stiver-909256.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>As a JavaScript developer, you've likely encountered different types of errors while coding. Most of the time these will be type errors or reference errors. But have you ever wondered what they mean?</p>
<p>Have you ever tried reading about the error type specified by the interpreter before solving these errors? If not, you should, since knowing about these errors can help you solve your problems.</p>
<p>For example, when you encounter an error, you probably Google it. You copy and paste the whole error and try to find out the solution, by visiting various websites and forums. It's a trial and error method of finding and solving bugs.</p>
<p>But what if you already knew why the error generally occurs? This would save you time you'd otherwise spend searching for solutions online. Instead, you could start looking for solutions on your own just by looking at the error type.</p>
<p>In this guide, you will learn about the two mostly encountered error types, which are type error and reference error. You'll learn why they occur, the difference between them, and how to avoid getting these errors.</p>
<p>Note: There are other types of errors in JavaScript like syntax errors, internal errors, range errors, and eval errors. But the scope of this article is limited to the two most commonly occurring errors.</p>
<h2 id="heading-what-is-a-type-error">What is a Type Error?</h2>
<p>Type errors occur when you use something that is not intended to be used in that particular way. For example, using a screwdriver to hammer in a nail, instead of using a hammer.</p>
<p>Let's understand this using an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> a = <span class="hljs-number">1</span>
<span class="hljs-built_in">console</span>.log(a()) 

<span class="hljs-comment">//output</span>
Uncaught <span class="hljs-built_in">TypeError</span>: a is not a <span class="hljs-function"><span class="hljs-keyword">function</span></span>
</code></pre>
<p>Here <code>a</code> is a variable initialized with a value. You encountered an error because you tried to call a function with the variable name. A variable cannot be called as a function. Functions and variables work differently. So in this case, you got a type error. You used the <code>let</code> variable differently from its <em>type.</em> </p>
<p>This gives us a type error.</p>
<p>Solution: To resolve this error, you must refer to the variable in the console, as it is intended to be used. In this case, you pass <code>a</code> as a variable instead of a function.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> a = <span class="hljs-number">1</span>
<span class="hljs-built_in">console</span>.log(a)

<span class="hljs-comment">//output</span>
<span class="hljs-number">1</span>
</code></pre>
<p>Let's take another example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> a = <span class="hljs-number">1</span>
a = <span class="hljs-number">2</span> <span class="hljs-comment">// you reassign a const type variable again</span>

<span class="hljs-comment">//output</span>
<span class="hljs-attr">TypeError</span>: Assignment to constant variable.
</code></pre>
<p>Here, we reassigned the <code>const</code> type variable <code>a</code> to a new value. But you can't change const variables like this, so in this case you get a type error</p>
<p>Solution: never reassign a <code>const</code> type variable once you've defined it.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> a = <span class="hljs-number">1</span>
<span class="hljs-keyword">const</span> b = <span class="hljs-number">2</span>
<span class="hljs-built_in">console</span>.log(a, b)

<span class="hljs-comment">//output</span>
<span class="hljs-number">1</span> <span class="hljs-number">2</span>
</code></pre>
<p>Here's another example using an array:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> myArray = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>]
myArray = myArray.push(<span class="hljs-number">5</span>) <span class="hljs-comment">// reassign array</span>

<span class="hljs-comment">//output</span>
<span class="hljs-attr">TypeError</span>: Assignment to constant variable.
</code></pre>
<p>In this case, we reassigned the <code>const</code> type <code>myArray</code>. This gives us a type error because again, this kind of reassignment is against the properties of <code>const</code>. </p>
<p>Solution:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> myArray = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>]
myArray.push(<span class="hljs-number">5</span>) <span class="hljs-comment">// you can push new values</span>

<span class="hljs-comment">//output</span>
[<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>]
</code></pre>
<p>You can easily push new values to the array without reassigning it. This will not give you any error. Pushing values into an array is allowed. This way you can avoid getting the error.</p>
<h3 id="heading-how-to-avoid-getting-a-type-error">How to avoid getting a type error</h3>
<p>The easiest way to prevent type errors is to avoid using the same names for different variables and functions. </p>
<p>If you use different names, you will not get confused or replace one with another, and you can easily avoid getting this error.</p>
<p>Another way is to make sure you use variables as they're intended to be used. Instead of using <code>const</code> when you need to reassign a value, use <code>let</code> (which allows this kind of change).</p>
<h2 id="heading-what-is-a-reference-error">What is a Reference Error?</h2>
<p>Reference errors occur when you are trying to refer to or use something that does not exist. For example, looking for a screwdriver in your toolbox, but it's not there.</p>
<p>Let's understand this using an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> a = <span class="hljs-number">1</span>
<span class="hljs-built_in">console</span>.log(b) <span class="hljs-comment">// undefined variable used</span>

<span class="hljs-comment">//output</span>
Uncaught <span class="hljs-built_in">ReferenceError</span>: b is not defined
</code></pre>
<p>Here, <code>a</code> is a variable initialized with a value. We encountered an error because we tried to console log the variable <code>b</code> that does not exist. We hadn't yet declared any such variable, so we got a reference error here.</p>
<p>Solution: only use a variable that you've declared to avoid getting an error.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> a = <span class="hljs-number">1</span>
<span class="hljs-built_in">console</span>.log(a) <span class="hljs-comment">// used defined variable</span>

<span class="hljs-comment">//output</span>
<span class="hljs-number">1</span>
</code></pre>
<p>Here's another example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span>(<span class="hljs-literal">true</span>){
    <span class="hljs-keyword">let</span> a = <span class="hljs-number">1</span>
}

<span class="hljs-built_in">console</span>.log(a)

<span class="hljs-comment">//output</span>
<span class="hljs-attr">ReferenceError</span>: a is not defined
</code></pre>
<p>In this example, we're trying to access the <code>a</code> variable of type <code>let</code> outside its block. The interpreter cannot find it outside the block. This gives us an error.</p>
<p>Solution:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span>(<span class="hljs-literal">true</span>){
    <span class="hljs-keyword">let</span> a = <span class="hljs-number">1</span>
    <span class="hljs-built_in">console</span>.log(a)
}


<span class="hljs-comment">//output</span>
<span class="hljs-number">1</span>
</code></pre>
<p>Using the variable inside its block or scope will not give you any error.</p>
<p>Let's take one more example, but this one can be difficult to understand.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span>(<span class="hljs-literal">true</span>){
    <span class="hljs-built_in">console</span>.log(a)
    <span class="hljs-keyword">let</span> a = <span class="hljs-number">1</span>
}


<span class="hljs-comment">//output</span>
<span class="hljs-attr">ReferenceError</span>: Cannot access <span class="hljs-string">'a'</span> before initialization
</code></pre>
<p><code>a</code> is still inside its scope. But we get an error. Why? Because we're trying to use the variable before we've defined it. This is not allowed and goes against the properties of the <code>let</code> variable. </p>
<p>Solution: use the <code>let</code> variable only after defining it. </p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span>(<span class="hljs-literal">true</span>){
    <span class="hljs-keyword">let</span> a = <span class="hljs-number">1</span>
    <span class="hljs-built_in">console</span>.log(a)

}

<span class="hljs-comment">//output</span>
<span class="hljs-number">1</span>
</code></pre>
<h3 id="heading-how-to-avoid-getting-a-reference-error">How to avoid getting a reference error</h3>
<p>The easiest way to avoid getting reference errors is to refer to or access only defined variables. Only use variables that exist. </p>
<p>You can also use conditional statements and error handling to avoid running code if a variable or a function does not exist.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>You can easily debug your code when you already know how to resolve your errors. It's good to know commonly occurring errors and how to avoid them. This will save you time searching for solutions online and wasting hours trying to find a solution when a little bit of knowledge and awareness about these things can help.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Handle Errors in Computer Networks ]]>
                </title>
                <description>
                    <![CDATA[ There are some magical things about the Internet, and one thing in particular is that it works. In spite of so many obstacles, we can deliver our packets over the globe, and do so fast. Even more specifically, one amazing thing about the Internet is ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-handle-errors-in-computer-networks/</link>
                <guid isPermaLink="false">66c17c3858ee0865d2671b5d</guid>
                
                    <category>
                        <![CDATA[ computer network ]]>
                    </category>
                
                    <category>
                        <![CDATA[ computer networking ]]>
                    </category>
                
                    <category>
                        <![CDATA[ error ]]>
                    </category>
                
                    <category>
                        <![CDATA[ error handling ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Omer Rosenbaum ]]>
                </dc:creator>
                <pubDate>Wed, 18 Jan 2023 16:05:43 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/01/Copy-of-Computer-Networks-Hub-Switch.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>There are some magical things about the Internet, and one thing in particular is that it works. In spite of so many obstacles, we can deliver our packets over the globe, and do so fast.</p>
<p>Even more specifically, one amazing thing about the Internet is its ability to handle errors. </p>
<p>What do I mean by errors? When a packet or a frame is received by a machine, we say it contains an error if the data that had been sent is not the data that was received. For instance, a single <code>1</code> was mistakenly received as a <code>0</code> after its transmission. </p>
<p>This can happen due to many different reasons. Perhaps there was some disturbance in the wire where the data was transmitted – say, a child rode her bicycle over the wire. Perhaps there was some collision in the air as many people transmitted at once. Maybe it was a device's error.</p>
<p>Regardless of the specific reason, you still get valid data on the Internet. Without handling errors, you may read the last sentence and instead of <code>errors</code> read <code>errbbb</code>. Weird, isn't it? So how does the Internet handle errors?</p>
<p>There are two main approaches for handling errors – detection, and correction. We shall start by describing detection, and then talk about correction.</p>
<h1 id="heading-what-is-error-detection">What is Error Detection?</h1>
<p>When dealing with error detection, we are looking for a boolean result – <code>True</code>, or <code>False</code>. Is the frame/packet valid, or not. That is all. We don’t want to know where the error occurred. If the frame is invalid, we will simply drop it.</p>
<p>So when the receiver receives a frame, they will determine whether an error has occurred. If the frame is valid, they will read it. If the frame contains errors - the receiver will drop it.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-84.png" alt="Image" width="600" height="400" loading="lazy">
_Error Detection: we only want to know if the frame/packet is valid or not. (<a target="_blank" href="https://www.youtube.com/watch?v=H_bYtVDF6T4&amp;ab_channel=Brief">Source: Brief</a>)_</p>
<p>One method for error detection is using a <strong>checksum</strong>. A common implementation of a checksum is called <strong>CRC – Cyclic Redundancy Check</strong>. </p>
<p>In this post we will not trouble ourselves with the mathematical implementation of CRCs in the real world (if you're interested, check out <a target="_blank" href="https://en.wikipedia.org/wiki/Cyclic_redundancy_check">Wikipedia</a>). Rather, we'll simply try to understand the concept. To do so, let’s implement a very simple checksum mechanism ourselves.</p>
<p>Consider a protocol for transmitting 10-digit phone numbers between endpoints. This protocol is extremely simple: each packet includes exactly 10 bytes, each one representing a digit. For example, a packet might include the following digits:</p>
<p><code>5551234567</code></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-85.png" alt="Image" width="600" height="400" loading="lazy">
_A packet with a payload of 10 digits (<a target="_blank" href="https://www.youtube.com/watch?v=H_bYtVDF6T4&amp;ab_channel=Brief">Source: Brief</a>)_</p>
<p>For simplicity's sake, we will omit the headers of the packet and focus solely on the payload. </p>
<p>Now, we will add a checksum. Say that we <strong>add</strong> all the digits. So in this example, we would calculate <code>5</code> + <code>5</code> +<code>5</code> +<code>1</code>+… all the way through <code>7</code>. We would get <code>43</code>. This would be our checksum value.</p>
<p>Now, the sender won’t only send the phone number, but also the checksum value right after it. In this example, the sender would send:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-86.png" alt="Image" width="600" height="400" loading="lazy">
_The packet's data is followed by a checksum. (<a target="_blank" href="https://www.youtube.com/watch?v=H_bYtVDF6T4&amp;ab_channel=Brief">Source: Brief</a>)_</p>
<p>Now, as the receiver, you can do the same thing. You will read the phone number, and calculate the checksum. You will add the digits, and get <code>43</code>. </p>
<p>Since you've received the correct result (that is, your calculation based on the data matches the checksum value sent in the packet), you can assume that the frame is valid.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-89.png" alt="Image" width="600" height="400" loading="lazy">
_The sender compares their calculated checksum value and the checksum in the packet. If the values match, the packet is assumed to be valid (<a target="_blank" href="https://www.youtube.com/watch?v=H_bYtVDF6T4&amp;ab_channel=Brief">Source: Brief</a>)_</p>
<p>What happens in case of an error? 🤔</p>
<p>Let’s say, for instance, that the digit <code>2</code> was replaced by an <code>8</code>. Now, even though the sender sent the same stream as before ( <code>555123456743</code> ), you, as the receiver, see something a bit different:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-90.png" alt="Image" width="600" height="400" loading="lazy">
_A packet containing an error (<a target="_blank" href="https://www.youtube.com/watch?v=H_bYtVDF6T4&amp;ab_channel=Brief">Source: Brief</a>)_</p>
<p>Now, you are calculating the checksum, adding all the digits. You get <code>49</code>. Since this value is different from the checksum value specified in the original frame, <code>43</code>, the frame is considered to be invalid and you drop it.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-91.png" alt="Image" width="600" height="400" loading="lazy">
_The sender compares their calculated checksum value and the checksum in the packet. If the values don't match, the packet is assumed to be invalid (<a target="_blank" href="https://www.youtube.com/watch?v=H_bYtVDF6T4&amp;ab_channel=Brief">Source: Brief</a>)_</p>
<p>Are there problems with this method? 🤔</p>
<p>Yes, there are. Consider, for example, what happens if there are two errors – and instead of the original stream ( <code>555123456743</code> ), you receive the following:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-92.png" alt="Image" width="600" height="400" loading="lazy">
_A packet received with two errors, resulting in the stream <code>456123456743</code> (<a target="_blank" href="https://www.youtube.com/watch?v=H_bYtVDF6T4&amp;ab_channel=Brief">Source: Brief</a>)_</p>
<p>What happens when you add the digits?</p>
<p>Even though the digits are not the same as the original packet, the checksum will remain correct, and the frame will be regarded as valid.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-93.png" alt="Image" width="600" height="400" loading="lazy">
_Despite the errors, the checksum value happens to be correct, resulting in a false assumption that the packet is valid (<a target="_blank" href="https://www.youtube.com/watch?v=H_bYtVDF6T4&amp;ab_channel=Brief">Source: Brief</a>)_</p>
<p>Real checksum functions, such as CRCs, are of course much better implemented than the one in our example – but in extremely rare cases, such problems may occur. </p>
<p>Notice that using this kind of method, error detection, we don’t know where the problem occurred, but only whether the frame is valid or not. If the checksum value is invalid, we assume that the frame is invalid and drop it.</p>
<h1 id="heading-what-is-error-correction">What is Error Correction?</h1>
<p>As mentioned earlier, detection is not the only way to handle errors. Another approach might be to find the error and correct it. How can we do that?</p>
<p>An extremely simple way would be to transmit the data many times – let’s say, three times. For example, the stream <code>5551234567</code> would be transmitted as follows:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-94.png" alt="Image" width="600" height="400" loading="lazy">
_Sending the same data multiple times (<a target="_blank" href="https://www.youtube.com/watch?v=H_bYtVDF6T4&amp;ab_channel=Brief">Source: Brief</a>)_</p>
<p>So we basically sent the data three times.</p>
<p>Now, in case of an error in one digit, the receiver can look at the other two digits, and choose the one that appears two times out of three.</p>
<p>So, for instance, if we had a problem and <code>2</code> was replaced with an <code>8</code>, the receiver would get this stream:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-95.png" alt="Image" width="600" height="400" loading="lazy">
_An error in one of the occurrences of the data (<a target="_blank" href="https://www.youtube.com/watch?v=H_bYtVDF6T4&amp;ab_channel=Brief">Source: Brief</a>)_</p>
<p>Now, as a receiver, you can say: “I have <code>2</code>, <code>8</code>, <code>2</code>… so it was probably <code>2</code> in the original message”.</p>
<p>Is this problematic? Well, in some rare cases, we might get the same error twice. So it is possible, even though unlikely, that two of the original twos have been received as eights.</p>
<p>So while the sender sent this stream:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-94.png" alt="Image" width="600" height="400" loading="lazy">
_Sending the same data multiple times (<a target="_blank" href="https://www.youtube.com/watch?v=H_bYtVDF6T4&amp;ab_channel=Brief">Source: Brief</a>)_</p>
<p>The first <code>2</code> was mistakenly read as an <code>8</code>, and also the second <code>2</code> was received as an <code>8</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-96.png" alt="Image" width="600" height="400" loading="lazy">
_Two identical errors; Rare, but possible (<a target="_blank" href="https://www.youtube.com/watch?v=H_bYtVDF6T4&amp;ab_channel=Brief">Source: Brief</a>)_</p>
<p> Now, it looks as if the original message included an <code>8</code>, and not a <code>2</code>.</p>
<p>What can you do in order to lower the probability of such scenario?</p>
<p>The most simple solution would be to simply send the data even more times. Let’s say, five times. So now we duplicate all the data, and send it 5 times in total… </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-97.png" alt="Image" width="600" height="400" loading="lazy">
_Sending the data five(!) times (<a target="_blank" href="https://www.youtube.com/watch?v=H_bYtVDF6T4&amp;ab_channel=Brief">Source: Brief</a>)_</p>
<p>Now, say that two errors occurred, and again two of the <code>2</code> digits were replaced with <code>8</code>s.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-98.png" alt="Image" width="600" height="400" loading="lazy">
_Two identical errors; Rare, but possible (<a target="_blank" href="https://www.youtube.com/watch?v=H_bYtVDF6T4&amp;ab_channel=Brief">Source: Brief</a>)_</p>
<p>Clearly, it is very unlikely to get the same error twice, but even in this case, we still get <code>2</code> three times, so as the receiver you can tell, with a high probability, that the original message contained a <code>2</code>, rather than an <code>8</code>.</p>
<h2 id="heading-whats-the-overhead">What's the Overhead?</h2>
<p>Now would be a good time to introduce the term <strong>overhead</strong>. When we say overhead, we basically mean data or time needed to convey the actual message. Let’s first understand what this term means in general, and then consider it in the context of handling errors.</p>
<p>Let’s say that I have a lesson to teach in my university. My goal is to teach the lesson itself, which is also called the <strong>payload</strong> in that context – that is, the actual data or message I would like to convey.</p>
<p>In order to teach the lesson, or to convey the payload, I first have to physically get to the university – so I get out of my home, walk to the bus station, wait for the bus, take the bus, get off the bus, walk to the building, wait for the lesson to start – and only then do I actually get to teach the lesson. </p>
<p>This entire process is <strong>overhead</strong> that I have to pay in order to deliver the <strong>payload</strong>, in this case – to teach the lesson.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-99.png" alt="Image" width="600" height="400" loading="lazy">
_Overhead and Payload are two extremely important terms in Computer Networks (<a target="_blank" href="https://www.youtube.com/watch?v=H_bYtVDF6T4&amp;ab_channel=Brief">Source: Brief</a>)_</p>
<p>The same applies in computer networks. Our <strong>payload</strong> is the data, and there is always some <strong>overhead</strong> associated with sending it. </p>
<h2 id="heading-back-to-handling-errors">Back to Handling Errors</h2>
<p>In the context here – sending the data three times, as suggested earlier, means that for every byte of payload we have two bytes of overhead. If we send the data five times, then for every byte of payload, we have four bytes of overhead. That’s a LOT!</p>
<p>Consider error <em>detection</em>, on the other hand. In our example protocol for sending phone numbers, how much overhead did we have?</p>
<p>Recall that for every ten-digit phone number, that is ten bytes, we included a two-digit checksum value. In other words, we had two bytes of overhead for ten bytes of payload. It is clear that in our example, error detection yields much smaller overhead in comparison to error correction.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-100.png" alt="Image" width="600" height="400" loading="lazy">
_In the sample protocol, for every ten-digit phone number (ten bytes of payload), we included a two-digit checksum value (two bytes of overhead) (<a target="_blank" href="https://www.youtube.com/watch?v=H_bYtVDF6T4&amp;ab_channel=Brief">Source: Brief</a>)_</p>
<p>There are better ways to achieve error correction with high accuracy than to simply send the data so many times, but they are more complicated and out of scope for this post. Even with very complicated error correction techniques, they still require lots of overhead when compared to error detection.</p>
<p>Also, notice that except for the bytes sent as overhead in case of error correction, error detection is much simpler. </p>
<h1 id="heading-error-correction-vs-error-detection-which-is-better">Error Correction vs Error Detection – Which is Better?</h1>
<p>We already concluded that error detection is simpler, and with a smaller payload compared to error correction.</p>
<h3 id="heading-so-when-would-we-prefer-error-correction">So, when would we prefer error correction?</h3>
<p>One case might be when we have a one-way link. That is, a network where we can only transfer data in one direction. </p>
<p>For example, say you have a secret agent that you need to send a message to. The agent knows that they need to look up to the sky at exactly midnight, and they will see a series of flashes indicating the secret message. </p>
<p>The secret agent cannot reply, or their location and identity will be revealed. In addition, you don’t want to send the message over and over again, as not to draw much attention, and to make it harder for someone to intercept the message.</p>
<p>In this case, you definitely want your agent to receive the exact message that you’ve sent. Consider a case where you want to send them the message “do not place the bomb”. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-101.png" alt="Image" width="600" height="400" loading="lazy">
_A sensitive message for a secret agent (<a target="_blank" href="https://www.youtube.com/watch?v=H_bYtVDF6T4&amp;ab_channel=Brief">Source: Brief</a>)_</p>
<p>Of course, you don’t want to risk the unfortunate scenario of the agent reading the message as “do <strong>now</strong> place the bomb”, due to an error.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-102.png" alt="Image" width="600" height="400" loading="lazy">
_An error may change the meaning of the message substantially (<a target="_blank" href="https://www.youtube.com/watch?v=H_bYtVDF6T4&amp;ab_channel=Brief">Source: Brief</a>)_</p>
<p>If you use error <em>detection</em>, the agent might be aware that the message they received is invalid in case of an error, but they won’t be able to tell you that they need you to send the message again. As you want the agent to be able to read your message correctly and without sending any data back to us, error correction is preferred.</p>
<p>So, one-way link is one case where we prefer error correction. What about other cases?</p>
<p>Sometimes you just <em>can’t</em> send the data again, perhaps because it has been erased from the memory of your machine. That is, the data is deleted right after it has been sent. In this case, you'd clearly prefer error correction, as sending the data again, as we would do with error detection, is just impossible.</p>
<p>Also, if sending the data again is possible, but extremely expensive, error correction may be preferable. </p>
<p>For example, if you send a message to the moon, say, with a spaceship – it might be really expensive to send it over again in case of an error. Using error correction, you send the data only once and the receiver should be able to deal with it, even if an error occurred.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/image-103.png" alt="Image" width="600" height="400" loading="lazy">
_Cases where correction is preferred (<a target="_blank" href="https://www.youtube.com/watch?v=H_bYtVDF6T4&amp;ab_channel=Brief">Source: Brief</a>)_</p>
<p>In general, we prefer error correction when retransmitting the data is costly or impossible. </p>
<h3 id="heading-when-would-we-prefer-error-detection">When would we prefer error detection?</h3>
<p>Well, in case we can retransmit the data, we usually prefer error detection since it comes with very little overhead compared to error correction. Especially, when sending the data is relatively cheap.</p>
<p>For example, on the Internet, if an error occurs when you send a frame, no problem – you can simply send it again! </p>
<p>For example, when I covered <a target="_blank" href="https://www.freecodecamp.org/news/the-complete-guide-to-the-ethernet-protocol/">the Ethernet protocol in a previous post</a>, I mentioned that Ethernet protocol uses change detection, namely <code>CRC32</code> – that is, 32 bits (or 4 bytes) of a checksum for every frame. </p>
<p>Note that it doesn’t mean that error detection is simply better. It just better fits the Internet than error correction. As mentioned before, error correction is preferable in other cases.</p>
<h1 id="heading-wrapping-up">Wrapping Up</h1>
<p>In this tutorial, we discussed various methods for handling errors. We looked at <strong>error detection</strong>, where we only know whether a frame is valid or not. We also considered <strong>error correction</strong>, where the receiver can restore the correct value of an erroneous frame. We also introduced the term <strong>overhead</strong>. </p>
<p>We then understood why we use error detection on the Internet, rather than error correction. Stay tuned for more posts in this series about Computer Networks 💪🏻</p>
<h2 id="heading-about-the-author"><strong>About the Author</strong></h2>
<p><a target="_blank" href="https://www.linkedin.com/in/omer-rosenbaum-034a08b9/">Omer Rosenbaum</a> is <a target="_blank" href="https://swimm.io/">Swimm</a>’s Chief Technology Officer. He's the author of the Brief <a target="_blank" href="https://youtube.com/@BriefVid">YouTube Channel</a>. He's also a cyber training expert and founder of Checkpoint Security Academy. He's the author of <a target="_blank" href="https://data.cyber.org.il/networks/networks.pdf">Computer Networks (in Hebrew)</a>. You can find him on <a target="_blank" href="https://twitter.com/Omer_Ros">Twitter</a>.</p>
<h2 id="heading-additional-resources"><strong>Additional Resources</strong></h2>
<ul>
<li><a target="_blank" href="https://www.youtube.com/playlist?list=PL9lx0DXCC4BMS7dB7vsrKI5wzFyVIk2Kg">Computer Networks Playlist - on my Brief channel</a></li>
<li><a target="_blank" href="https://en.wikipedia.org/wiki/Cyclic_redundancy_check">CRC - Wikipedia</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/the-complete-guide-to-the-ethernet-protocol/">The Complete Guide to Ethernet Protocol</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ iferror Function in Excel ]]>
                </title>
                <description>
                    <![CDATA[ You can use the IFERROR function to catch errors in Excel. Using the function's parameters, you can return a custom value when specific errors occur.  In this article, you'll learn how to use the IFERROR function to evaluate and handle errors in Exce... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/iferror-function-in-excel-example/</link>
                <guid isPermaLink="false">66b0a2fbb23875658c0760b5</guid>
                
                    <category>
                        <![CDATA[ error handling ]]>
                    </category>
                
                    <category>
                        <![CDATA[ excel ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ihechikara Abba ]]>
                </dc:creator>
                <pubDate>Mon, 09 Jan 2023 15:21:52 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/01/rubaitul-azad-GauA0hiEwDk-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>You can use the <code>IFERROR</code> function to catch errors in Excel. Using the function's parameters, you can return a custom value when specific errors occur. </p>
<p>In this article, you'll learn how to use the <code>IFERROR</code> function to evaluate and handle errors in Excel. You can use the <code>IFERROR</code> function to handle <code>#N/A</code>, <code>#VALUE!</code>, <code>#REF!</code>, <code>#DIV/0!</code>, <code>#NUM!</code>, <code>#NAME?</code>, or <code>#NULL!</code> errors.</p>
<h2 id="heading-iferror-function-syntax-in-excel">IFERROR Function Syntax in Excel</h2>
<p>Here's what the syntax for the the <code>IFERROR</code> function looks like:</p>
<pre><code class="lang-txt">IFERROR(value, value_if_error)
</code></pre>
<p>As you can see above, the <code>IFERROR</code> function has two parameters: <code>value</code> and <code>value_if_error</code>. </p>
<ul>
<li><code>value</code> denotes the value to be checked for an error.</li>
<li><code>value_if_error</code> is returned if the value checked throws an error. </li>
</ul>
<p>The parameters above will make more sense with the examples that follow. </p>
<h2 id="heading-how-to-use-the-iferror-function-in-excel">How to Use the <code>IFERROR</code> Function in Excel</h2>
<p>In this section, you'll see a practical application of the the <code>IFERROR</code> function. </p>
<p>Here's the table we'll be working with: </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/iferror-1.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In the table above, we have three columns: <strong>Data 1</strong>, <strong>Data 2</strong>, and <strong>Quotient</strong>. </p>
<p>The idea here is to fill the third column (<strong>Quotient</strong>) with the result gotten from dividing <strong>Data 1</strong> by <strong>Data 2.</strong> </p>
<p>That is:</p>
<p>For row one: 80/192<br>For row two: 75/180. And so on. </p>
<p>But if you look closely, some rows have values that will lead to mathematical errors — row 4 and row 6. </p>
<p>We cannot divide 60 by 0 on row 4, nor can we divide 65 by NIL on row 6. </p>
<p>Here's what the table will look like after the divisions: </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/iferror1.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The quotient for column 4 and 6 are <code>#DIV/0!</code> and <code>#VALUE!</code>, respectively. This is because the operation being performed leads to a math error. </p>
<p>We cannot fix this mathematically, but we can catch errors like these and return a custom value for them. Here's how using the <code>IFERROR</code> function:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/iferror3.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p>I've removed every value in the <strong>Quotient</strong> column. Next, we'll use the <code>IFERROR</code> function. That is:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/iferror4.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In the first <strong>Quotient</strong> row, we wrote the <code>IFERROR</code> function: <code>=IFERROR(A2/B2, 0)</code>. The two parameters are <strong>A2/B2</strong> and <strong>0</strong>.</p>
<p>The first parameter <strong>A2/B2</strong> denotes <strong>A2</strong> (80) divided by row <strong>B2</strong> (192). If the division is possible, the quotient will be returned. </p>
<p>If the division is not possible, the second parameter (<strong>0</strong>) will be returned. </p>
<p>So our table will look like this after the <code>IFERROR</code> function is applied in each row: </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/iferror5.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now row 4 and 6 have 0 as their quotient instead of <code>#DIV/0!</code> and <code>#VALUE!</code>, respectively. </p>
<p>Note that you can use a custom message as well instead of 0. That is:  <code>=IFERROR(A2/B2, "Division not possible")</code>. You have to nest the text in quotation marks. We'll have a table like this: </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/iferror6.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p>So it's up to you to customize what will be returned if there is an error. </p>
<h2 id="heading-summary">Summary</h2>
<p>In this article, we talked about the <code>IFERROR</code> function in Excel. It can be used to handle <code>#N/A</code>, <code>#VALUE!</code>, <code>#REF!</code>, <code>#DIV/0!</code>, <code>#NUM!</code>, <code>#NAME?</code>, or <code>#NULL!</code> errors. </p>
<p>We saw the syntax for using the <code>IFERROR</code> function and the meaning of its parameters. </p>
<p>We also saw some examples that showed how to use the <code>IFERROR</code> function in an Excel table. </p>
<p>Thank you for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ TypeError: can't multiply sequence by non-int of type float [Solved Python Error] ]]>
                </title>
                <description>
                    <![CDATA[ Most times when you encounter errors while coding, you can discover the reason why the error is occurring and how you can fix it in the error message.  The Python error, "TypeError: can't multiply sequence by non-int of type float" is no exception to... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/typeerror-cant-multiply-sequence-by-non-int-of-type-float-solved-python-error-3/</link>
                <guid isPermaLink="false">66adf23c11a28b6eb378d2cb</guid>
                
                    <category>
                        <![CDATA[ error ]]>
                    </category>
                
                    <category>
                        <![CDATA[ error handling ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kolade Chris ]]>
                </dc:creator>
                <pubDate>Wed, 21 Dec 2022 21:13:46 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/12/pexels-polina-zimmerman-3747132.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Most times when you encounter errors while coding, you can discover the reason why the error is occurring and how you can fix it in the error message. </p>
<p>The Python error, "TypeError: can't multiply sequence by non-int of type float" is no exception to that.</p>
<p>I have prepared this article to show you why this error occurs and how you can fix it. Read on.</p>
<h2 id="heading-why-the-typeerror-cant-multiply-sequence-by-non-int-of-type-float-error-occurs">Why the "TypeError: can't multiply sequence by non-int of type float" Error Occurs</h2>
<p>To understand why you get the error "TypeError: can't multiply sequence by non-int of type float", let's look at the keywords in the error: <strong>Typeerror</strong>, <strong>multiply</strong>, <strong>sequence</strong>, and <strong>type float</strong>.</p>
<ul>
<li><strong>Typeerror</strong> is an exception thrown when you put together inappropriate data types in an operation</li>
<li><strong>multiply</strong> in the error means you're trying to perform a multiplication</li>
<li><strong>sequence</strong> is an ordered set in Python. It could be strings, lists, or tuples.</li>
<li><strong>type float</strong> means there's a decimal number in the operation you're trying to perform, for example, 2.4 or 5.40</li>
</ul>
<p>So, if you're getting this error, it means you're multiplying any of those sequences (usually a string and a tuple) with a floating point number (decimal number).</p>
<p>Indeed, you can multiply a sequence with a number and Python will do the work properly:</p>
<pre><code class="lang-py">site_name = <span class="hljs-string">'freeCodeCamp '</span>

print(site_name * <span class="hljs-number">2</span>)
<span class="hljs-comment"># freeCodeCamp freeCodeCamp </span>

print(site_name * <span class="hljs-number">3</span>)
<span class="hljs-comment"># freeCodeCamp freeCodeCamp freeCodeCamp</span>
</code></pre>
<pre><code class="lang-py">stringfied_num = <span class="hljs-string">'10 '</span>

print(stringfied_num * <span class="hljs-number">3</span>)
<span class="hljs-comment"># 10 10 10</span>
</code></pre>
<p>Same thing also works for tuples:</p>
<pre><code class="lang-py">myTuple = (<span class="hljs-number">4</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>)
print(myTuple * <span class="hljs-number">2</span>)

<span class="hljs-comment"># (4, 3, 4, 4, 3, 4)</span>
</code></pre>
<p>But if you try to do the multiplication with a decimal point number, you get the error "TypeError: can't multiply sequence by non-int of type float":</p>
<pre><code class="lang-py">site_name = <span class="hljs-string">'freeCodeCamp '</span>

print(site_name * <span class="hljs-number">2.5</span>)
<span class="hljs-comment"># Traceback (most recent call last):  </span>
<span class="hljs-comment">#   File "seq.py", line 3, in &lt;module&gt;</span>
<span class="hljs-comment">#     print(site_name * 2.5)</span>
<span class="hljs-comment"># TypeError: can't multiply sequence by non-int of type 'float'</span>
</code></pre>
<pre><code class="lang-py">myTuple = (<span class="hljs-number">4</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>)
print(myTuple * <span class="hljs-number">2.2</span>)

<span class="hljs-comment"># Traceback (most recent call last):   </span>
<span class="hljs-comment">#   File "seq.py", line 11, in &lt;module&gt;</span>
<span class="hljs-comment">#     print(myTuple * 2.2)</span>
<span class="hljs-comment"># TypeError: can't multiply sequence by non-int of type 'float'</span>
</code></pre>
<h2 id="heading-how-to-fix-the-typeerror-cant-multiply-sequence-by-non-int-of-type-float-error">How to Fix the "TypeError: can't multiply sequence by non-int of type 'float'" Error</h2>
<p>To fix the error "TypeError: can't multiply sequence by non-int of type 'float'", make sure you're not multiplying the string or tuple with a decimal point number. </p>
<p>So instead of multiplying the string or tuple with a floating point number, use an integer. For instance <code>"freeCodeCamp" * 5</code> instead of <code>"freeCodeCamp" * 5.6</code>:</p>
<pre><code class="lang-py">site_name = <span class="hljs-string">'freeCodeCamp '</span>
print(site_name * <span class="hljs-number">5</span>)

<span class="hljs-comment"># freeCodeCamp freeCodeCamp freeCodeCamp freeCodeCamp freeCodeCamp</span>
</code></pre>
<p>If you're dealing with a number in strings, for example, "10", you can convert the string to an integer with the <code>int()</code> method and to float with the <code>float()</code> method:</p>
<pre><code class="lang-py">stringfied_num = <span class="hljs-string">'10 '</span>

print(int(stringfied_num) * <span class="hljs-number">3</span>)
<span class="hljs-comment"># 30</span>
</code></pre>
<pre><code class="lang-py">stringfied_num = <span class="hljs-string">'10 '</span>

print(float(stringfied_num) * <span class="hljs-number">3</span>)
<span class="hljs-comment"># 30</span>
</code></pre>
<p>If you're dealing with a user input, you can also find a way to convert the floating-point number to an integer. In fact, you should handle the possibility of the user entering a decimal point number instead of a straight integer:</p>
<pre><code class="lang-py"><span class="hljs-comment"># declare a string variable</span>
site_name = <span class="hljs-string">'freeCodeCamp '</span>

<span class="hljs-comment"># Get the user input and convert it to a decimal number</span>
user_input = float(input(<span class="hljs-string">"Enter a number: "</span>))

<span class="hljs-comment"># Round the number entered by the user to the nearest whole number</span>
rounded_input = round(user_input)

<span class="hljs-comment"># Multiply the site_name variable by the user input</span>
result = rounded_input * site_name

<span class="hljs-comment"># Print the result to the console</span>
print(result)

<span class="hljs-comment"># I entered 3.6 and the result was: freeCodeCamp freeCodeCamp freeCodeCamp freeCodeCamp</span>
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>You cannot multiply a sequence by a floating point number. What you get if you do that is the error, TypeError: can't multiply sequence by non-int of type 'float'. That's why this article was dedicated to letting you know how to fix the error.</p>
<p>The takeaway from this article is that if you're using any string as a number, you should make sure they are converted with the <code>float()</code> method – especially if they are used in a calculation.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Cannot use import statement outside a module [React TypeScript Error Solved] ]]>
                </title>
                <description>
                    <![CDATA[ When building a web application, you may encounter the SyntaxError: Cannot use import statement outside a module error.  This error might be raised when using either JavaScript or TypeScript in the back-end. So you could be working on the client side... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/cannot-use-import-statement-outside-a-module-react-typescript-error-solved/</link>
                <guid isPermaLink="false">66b0a27f675b17049e0b4be0</guid>
                
                    <category>
                        <![CDATA[ error ]]>
                    </category>
                
                    <category>
                        <![CDATA[ error handling ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ node ]]>
                    </category>
                
                    <category>
                        <![CDATA[ node js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ TypeScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ihechikara Abba ]]>
                </dc:creator>
                <pubDate>Tue, 15 Nov 2022 15:30:56 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/11/markus-spiske-iar-afB0QQw-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>When building a web application, you may encounter the <code>SyntaxError: Cannot use import statement outside a module</code> error. </p>
<p>This error might be raised when using either JavaScript or TypeScript in the back-end. So you could be working on the client side with React, Vue, and so on, and still run into this error. </p>
<p>You can also encounter this error when working with JavaScript on the client side. </p>
<p>In this article, you'll learn how to fix the <code>SyntaxError: Cannot use import statement outside a module</code> error when using TypeScript or JavaScript with <a target="_blank" href="https://www.freecodecamp.org/news/node-js-server-side-javascript-what-is-node-used-for/">Node</a>. </p>
<p>You'll also learn how to fix the error when working with JavaScript on the client side. </p>
<h2 id="heading-how-to-fix-the-typescript-syntaxerror-cannot-use-import-statement-outside-a-module-error">How to Fix the TypeScript <code>SyntaxError: Cannot use import statement outside a module</code> Error</h2>
<p>In this section, we'll work with a basic Node server using Express. </p>
<p>Note that if you're using the latest version of TypeScript for your Node app, the <strong>tsconfig.json</strong> file has default rules that prevent the <code>SyntaxError: Cannot use import statement outside a module</code> error from being raised.</p>
<p>So you're most likely not going to encounter the <code>SyntaxError: Cannot use import statement outside a module</code> error if you:</p>
<ul>
<li>Install the latest version of TypeScript, and are using the default <strong>tsconfig.json</strong> file that is generated when you run <code>tsc init</code> with the latest version.</li>
<li>Setup TypeScript correctly for Node and install the necessary packages.</li>
</ul>
<p>But let's assume you're not using the latest <strong>tsconfig.json</strong> file configurations.</p>
<p>Here's an Express server that listens on port 3000 and logs "Hello World!" to the console:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> express <span class="hljs-keyword">from</span> <span class="hljs-string">"express"</span>

<span class="hljs-keyword">const</span> app = express()

app.listen(<span class="hljs-string">"3000"</span>, (): <span class="hljs-function"><span class="hljs-params">void</span> =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello World!"</span>)
    <span class="hljs-comment">// SyntaxError: Cannot use import statement outside a module</span>
})
</code></pre>
<p>The code above looks as though it should run perfectly but the <code>SyntaxError: Cannot use import statement outside a module</code> is raised. </p>
<p>This is happening because we used the <code>import</code> keyword to import a module: <code>import express from "express"</code>. </p>
<p>To fix this, head over to the <strong>tsconfig.json</strong> file and scroll to the modules section.</p>
<p>You should see a particular rule like this under the modules section:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">/* Modules */</span>
<span class="hljs-string">"module"</span>: <span class="hljs-string">"esnext"</span>
</code></pre>
<p>To fix the problem, change the value "esnext" to "commonjs". </p>
<p>That is:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">/* Modules */</span>
<span class="hljs-string">"module"</span>: <span class="hljs-string">"commonjs"</span>
</code></pre>
<h2 id="heading-how-to-fix-the-javascript-syntaxerror-cannot-use-import-statement-outside-a-module-error">How to Fix the JavaScript <code>SyntaxError: Cannot use import statement outside a module</code> Error</h2>
<p>Fixing the <code>SyntaxError: Cannot use import statement outside a module</code> error when using vanilla JS is a bit different from TypeScript. </p>
<p>Here's our server:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> express <span class="hljs-keyword">from</span> <span class="hljs-string">"express"</span>;

<span class="hljs-keyword">const</span> app = express();

app.listen(<span class="hljs-number">3000</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello World!"</span>);
    <span class="hljs-comment">// SyntaxError: Cannot use import statement outside a module</span>
});
</code></pre>
<p>We're getting the <code>SyntaxError: Cannot use import statement outside a module</code> error for the same reason — we used the <code>import</code> keyword to import a module. </p>
<p>To fix this, go to the <strong>package.json</strong> file and add <code>"type": "module",</code>. That is:</p>
<pre><code class="lang-javascript">{
  <span class="hljs-string">"name"</span>: <span class="hljs-string">"js"</span>,
  <span class="hljs-string">"version"</span>: <span class="hljs-string">"1.0.0"</span>,
  <span class="hljs-string">"description"</span>: <span class="hljs-string">""</span>,
  <span class="hljs-string">"main"</span>: <span class="hljs-string">"app.js"</span>,
  <span class="hljs-string">"type"</span>: <span class="hljs-string">"module"</span>,
  <span class="hljs-string">"scripts"</span>: {
    <span class="hljs-string">"test"</span>: <span class="hljs-string">"echo \"Error: no test specified\" &amp;&amp; exit 1"</span>
  },
  <span class="hljs-string">"keywords"</span>: [],
  <span class="hljs-string">"author"</span>: <span class="hljs-string">""</span>,
  <span class="hljs-string">"license"</span>: <span class="hljs-string">"ISC"</span>,
  <span class="hljs-string">"dependencies"</span>: {
    <span class="hljs-string">"express"</span>: <span class="hljs-string">"^4.18.2"</span>
  }
}
</code></pre>
<p>Now you can use the <code>import</code> keyword without getting an error.</p>
<p>To fix this error when working with JavaScript on the client side (without any frameworks), simply add the attribute <code>type="module"</code> to the script tag of the file you want to import as a module. That is:</p>
<pre><code>&lt;script type=<span class="hljs-string">"module"</span> src=<span class="hljs-string">"./add.js"</span>&gt;&lt;/script&gt;
</code></pre><h2 id="heading-summary">Summary</h2>
<p>In this article, we talked about the <code>SyntaxError: Cannot use import statement outside a module</code> error in TypeScript and JavaScript. </p>
<p>This error mainly occurs when you use the <code>import</code> keyword to import a module in Node.js. Or when you omit the <code>type="module"</code> attribute in a <code>script</code> tag.</p>
<p>We saw code examples that raised the error and how to fix them when working with TypeScript and JavaScript.</p>
<p>Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Error: error:0308010c:digital envelope routines::unsupported [Node Error Solved] ]]>
                </title>
                <description>
                    <![CDATA[ If you work with Node.js and command line interface solutions like Webpack, create-react-app, or vue-cli-service, you might have encountered the error, Error: error:0308010c:digital envelope routines::unsupported.  You’re not alone, because I’m curre... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/error-error-0308010c-digital-envelope-routines-unsupported-node-error-solved/</link>
                <guid isPermaLink="false">66adf0c7b0efb2bf012fd7b7</guid>
                
                    <category>
                        <![CDATA[ error ]]>
                    </category>
                
                    <category>
                        <![CDATA[ error handling ]]>
                    </category>
                
                    <category>
                        <![CDATA[ node ]]>
                    </category>
                
                    <category>
                        <![CDATA[ node js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kolade Chris ]]>
                </dc:creator>
                <pubDate>Thu, 10 Nov 2022 18:39:19 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/11/envelope-1829509_1280.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you work with Node.js and command line interface solutions like Webpack, create-react-app, or vue-cli-service, you might have encountered the error, <code>Error: error:0308010c:digital envelope routines::unsupported</code>. </p>
<p>You’re not alone, because I’m currently getting it too:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/ss1-1.png" alt="ss1-1" width="600" height="400" loading="lazy"></p>
<p>The React app indeed failed to start:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/ss2-1.png" alt="ss2-1" width="600" height="400" loading="lazy"> </p>
<p>In this article, you’ll learn how to fix this error in 3 ways. But first, let’s discuss what causes the error.</p>
<h2 id="heading-what-causes-the-0308010cdigital-envelope-routinesunsupported-error">What Causes the "0308010c:digital envelope routines::unsupported" Error?</h2>
<p>You are likely getting this error because of 2 main reasons:</p>
<ul>
<li>you’re not using the LTS (long term support) version of Node JS. You can see I’m using Node 17.0.0, which is not an LTS version of Node. </li>
<li>you’re using react-script with a version less than 5</li>
</ul>
<p>The error can also occur because you’re using Node 17.</p>
<h2 id="heading-how-to-fix-the-0308010cdigital-envelope-routinesunsupported-error">How to Fix the "0308010c:digital envelope routines::unsupported" Error</h2>
<p>There are at least 3 ways by which you can fix this error. We are going to look at them one by one. Any of them should work for you.</p>
<h3 id="heading-pass-openssl-legacy-provider-to-webpack-or-the-cli-tool">Pass <code>--openssl-legacy-provider</code> to Webpack or the CLI Tool</h3>
<p>In a React app, for instance, you can pass <code>--openssl-legacy-provider</code> to the start script like this <code>"react-scripts --openssl-legacy-provider start"</code>.</p>
<p>That should do it. But if this fails to fix the error, then proceed to the next fix. On many occasions, it works.</p>
<h3 id="heading-use-an-lts-version-of-node-js">Use an LTS Version of Node JS</h3>
<p>Consider downgrading your Node version to 16.16.0 or other LTS versions. </p>
<p>Currently, 18.12.1 is the latest LTS version of Node. You can download it from the Node JS official website or use NVM to install it.</p>
<h3 id="heading-upgrade-react-script-to-version-5">Upgrade React Script to Version 5+</h3>
<p>If you’re working with React and this still fails to fix the error for you, then it’s likely an issue with your React script. </p>
<p>If you’re using a React script version less than 5, then you should upgrade it to version 5+.</p>
<p>In my case, I’m currently using react-scripts 3.4.3:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/ss3.png" alt="ss3" width="600" height="400" loading="lazy"> </p>
<p>To upgrade react-scripts to 5+, you can do it in two ways:</p>
<ul>
<li><p>Uninstall and reinstall react-scripts</p>
<ul>
<li>open the terminal and run <code>npm uninstall react-scripts</code></li>
<li>run <code>npm install react-scripts</code></li>
</ul>
</li>
<li><p>Manually change the react script version</p>
<ul>
<li>go to your <code>package.json</code> and change the react-script version to 5.0.2</li>
<li>delete the node_modules folder by running <code>rm –rf node_modules</code></li>
<li>delete the package.lock.json file by running <code>rm –rf package.lock.json</code></li>
<li>run <code>npm install</code> or <code>yarn add</code>, depending on the package manager you’re using</li>
</ul>
</li>
</ul>
<p>After upgrading the version of react-scripts to 5+, my React app is now working fine:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/ss4.png" alt="ss4" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/ss5.png" alt="ss5" width="600" height="400" loading="lazy"> </p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>As already pointed out in this article, if you are getting the "0308010c:digital envelope routines::unsupported" error, then it could happen you’re not using an LTS version of Node JS, or you’re using react-scripts version &lt;5.</p>
<p>Hopefully the fixes we discussed in this tutorial help you fix this error. If any of the fixes fail to work for you, then you should try the others. In my case, upgrading react-scripts to 5+ was what worked for me.</p>
<p>Thank you for reading.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
