{"id":8766,"date":"2021-03-08T17:29:00","date_gmt":"2021-03-08T11:59:00","guid":{"rendered":"https:\/\/www.h2kinfosys.com\/blog\/?p=8766"},"modified":"2021-03-08T17:30:35","modified_gmt":"2021-03-08T12:00:35","slug":"python-exception-handling","status":"publish","type":"post","link":"https:\/\/www.h2kinfosys.com\/blog\/python-exception-handling\/","title":{"rendered":"Python Exception Handling"},"content":{"rendered":"\n<p>An exception is a kind of error that occurs at runtime. Exceptions are different from errors as some of them can be dealt with without the program crashing. For instance, if you write a program to divide two numbers from a user. You must ensure that the denominator is not 0 as a number divided by zero is not defined.&nbsp;<\/p>\n\n\n\n<p>But rather than the user\u2019s input crashing your program, you could raise an exception that warns the user about the denominator being a non-zero number. General errors such as syntax errors cannot be dealt with in such a manner as the program is bound to crash when encountered. In this tutorial, we will discuss how to handle exceptions in Python using keywords such as try, except, raise, finally. By the end of this tutorial, you will learn:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Common Exceptions in Python<\/li><li>Why Using Exceptions is Important<\/li><li>Using the Try and Except <a href=\"https:\/\/www.h2kinfosys.com\/blog\/different-types-of-exception-handling-in-selenium-webdriver\/\" class=\"rank-math-link\">Statements to Handle Exceptions<\/a><\/li><li>Using the Finally Statement\u00a0<\/li><li>Using the raise Statement<\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Common Exceptions in Python<\/h2>\n\n\n\n<ul class=\"wp-block-list\"><li>AssertionError: This is raise when an assert statement is not true<\/li><li>AttributeError: This is raised when the assignment of a reference or attribute fails.\u00a0<\/li><li>FloatingPointError: This is raised when a floating-point operation fails.<\/li><li>ImportError: This is raised when the module you want to import is not found<\/li><li>IndexError: This is raised when the <a href=\"https:\/\/en.wikipedia.org\/wiki\/Iterator_pattern\" class=\"rank-math-link\" rel=\"nofollow noopener\" target=\"_blank\">index of an iterators<\/a> runs out of range<\/li><li>MemoryError: This is raised when your system runs out of memory. Maybe in an infinite loop for instance.\u00a0<\/li><li>NameError: This is raised when a variable to be used is not defined<\/li><li>ValueError: This is raised when a function receives an incorrect value as an argument even if the datatype was correct<\/li><li>ZeroDivisionError: This is raised when the denominator of a division operation is zero.\u00a0<\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Why Using Exceptions is Important<\/h2>\n\n\n\n<ul class=\"wp-block-list\"><li>With errors, you can set apart error handling codes from normal code<\/li><li>It prevents your code from crashing completely<\/li><li>It makes your code readable by others<\/li><li>It guides the programmer on the kind of inputs to expect from the end-users<\/li><li>You can raise your exception using the raise statement&nbsp;<\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Using the Try and Except Statements to Handle Exceptions&nbsp;<\/h2>\n\n\n\n<p>Errors are generally handled using the try and except statement. The codes in the try block are codes that you may accept some errors during runtime and want to handle. Let\u2019s see a simple example. We will write a code that receives 2 numbers from a user and then divides them.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">#the program divides a by b\na = float(input('Enter the numerator: '))\nb = float(input('Enter the denominator: '))\n\u00a0\nresult = a \/ b\n\u00a0\nprint(f\"{a} \/ {b} = {result}\")\nprint('Done with the program')<\/pre>\n\n\n\n<p>Let\u2019s say, the user enters 7 as numerator and 2 as the denominator.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Output:\nEnter the numerator: 7\nEnter the denominator: 2\n7.0 \/ 2.0 = 3.5\nDone with the program\n<\/code><\/pre>\n\n\n\n<p>All ran smoothly. But a user may enter 0 as the denominator. Assuming the user enters 7 and 0. What would be the output?<\/p>\n\n\n\n<p>Enter the numerator: 7<br>Enter the denominator: 0<br>Traceback (most recent call last):<\/p>\n\n\n\n<p>\u00a0\u00a0File &#8220;c:\/Users\/DELL\/Desktop\/pycodes\/__pycache__\/strings.py&#8221;, line 17, in &lt;module>\u00a0\u00a0\u00a0\u00a0<br>       result = a \/ b<br>ZeroDivisionError: float division by zero<\/p>\n\n\n\n<p>It throws an error. Notice that the last line of code \u2018Done with the program\u2019 was not printed. This means that the code has stopped abruptly at the point where the exception was encountered. In reality, this is not a good way of writing codes as a user\u2019s error can completely mar the code from performing any task.&nbsp;<\/p>\n\n\n\n<p>When you place the code in a try block, the Python interpreter knows that you wish to handle exceptions encountered. The except block indicates the error you want to track and the kind of message you wish to print.&nbsp;<\/p>\n\n\n\n<p>Let\u2019s have the syntax of the try and except statement.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">try:\n\u00a0\u00a0\u00a0\u00a0#insert the block of code\n\u00a0\u00a0\u00a0\u00a0\nexcept Exception:\n\u00a0\u00a0\u00a0\u00a0#insert the kind of message to be printed<\/pre>\n\n\n\n<p>Now, let\u2019s put the error code inside a try-except block to handle the ZeroDivisionError.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">#the program divides a by b\na = float(input('Enter the numerator: '))\nb = float(input('Enter the denominator: '))\n\u00a0\ntry:\n\u00a0\u00a0\u00a0\u00a0result = a \/ b\n\u00a0\u00a0\u00a0\u00a0print(f\"{a} \/ {b} = {result}\")\n\u00a0\nexcept Exception as e:\n\u00a0\u00a0\u00a0\u00a0print(e)\n\u00a0\u00a0\u00a0\u00a0print()\n\u00a0\u00a0\u00a0\u00a0print('Please enter a non-zero digit to fix this error')\n\u00a0\nprint('Done with the program')<\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Output:\nEnter the numerator: 7\nEnter the denominator: 0\nfloat division by zero\n<\/code><\/pre>\n\n\n\n<p>Please enter a non-zero digit to fix this error<\/p>\n\n\n\n<p>Done with the program<\/p>\n\n\n\n<p>Observe the output. It says float division by zero. Then print my custom message, \u2018Please enter a non-zero digit to fix this error\u2019. Lastly, it runs the last line of code, \u2018Done with the program\u2019. This shows that the code was run completely even with the error.&nbsp;<\/p>\n\n\n\n<p>Alternatively, you may specify the type of error you are expecting and write a custom message. For instance, I can write except ZeroDivisionError rather than except Exception as e. This is a much better way of handling errors as it specifies the kind of error to catch. Let\u2019s change our code slightly to reflect the ZeroDivisionError.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">#the program divides a by b\na = float(input('Enter the numerator: '))\nb = float(input('Enter the denominator: '))\n\u00a0\ntry:\n\u00a0\u00a0\u00a0\u00a0result = a \/ b\n\u00a0\u00a0\u00a0\u00a0print(f\"{a} \/ {b} = {result}\")\n\u00a0\nexcept ZeroDivisionError:\n\u00a0\u00a0\u00a0\u00a0print('Please enter a non-zero digit to fix this error')\n\u00a0\nprint('Done with the program')<\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Output:\nEnter the numerator: 7\nEnter the denominator: 0\nPlease enter a non-zero digit to fix this error\nDone with the program\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Using the Finally Statement&nbsp;<\/h2>\n\n\n\n<p>Codes that you want to get run whether or not an error was encountered are placed in the finally block. For instance, if you are dealing with a file or database and you want such a database to be closed as the last step. The code should be placed in the finally block.&nbsp;<\/p>\n\n\n\n<p>In our previous examples, the last line of code where we printed \u2018Done with the program\u2019 can be placed in a finally block because we want this code to be run no matter what. Let us tweak the code further.\u00a0<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">#the program divides a by b\na = float(input('Enter the numerator: '))\nb = float(input('Enter the denominator: '))\n\u00a0\ntry:\n\u00a0\u00a0\u00a0\u00a0result = a \/ b\n\u00a0\u00a0\u00a0\u00a0print(f\"{a} \/ {b} = {result}\")\n\u00a0\nexcept ZeroDivisionError:\n\u00a0\u00a0\u00a0\u00a0print('Please enter a non-zero digit to fix this error')\n\u00a0\nfinally:\n\u00a0\u00a0\u00a0\u00a0print('Done with the program')<\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Output:\nEnter the numerator: 7\nEnter the denominator: 0\nPlease enter a non-zero digit to fix this error\nDone with the program\n<\/code><\/pre>\n\n\n\n<p>As seen the result is like the previous. This is however a cleaner way of writing Python codes.&nbsp;<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Using the raise Statement<\/h2>\n\n\n\n<p>The raise statement is used for creating exceptions on your own. If you wish to handle an error when something happens, you can state the condition with an if statement, then write how you wish to handle the error in the raise block. See the syntax below.\u00a0<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">try:\n# \u00a0 \u00a0 some code is entered here\n\u00a0\u00a0\u00a0\u00a0if (#state some condition):\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0raise #do something<\/pre>\n\n\n\n<p>Let\u2019s use the raise statement in our earlier code.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">#the program divides a by b\na = float(input('Enter the numerator: '))\nb = float(input('Enter the denominator: '))\n\u00a0\ntry:\n\u00a0\u00a0\u00a0\u00a0result = a \/ b\n\u00a0\u00a0\u00a0\u00a0print(f\"{a} \/ {b} = {result}\")\n\u00a0\u00a0\u00a0\u00a0if b == 0.0:\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0raise ZeroDivisionError\n\u00a0\nfinally:\n\u00a0\u00a0\u00a0\u00a0print('Done with the program')<\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Output:\nEnter the numerator: 7\nEnter the denominator: 0.0\nDone with the program\nTraceback (most recent call last):\n  File \"c:\/Users\/DELL\/Desktop\/pycodes\/__pycache__\/strings.py\", line 16, in &lt;module>\n    result = a \/ b\nZeroDivisionError: float division by zero\n<\/code><\/pre>\n\n\n\n<p>As seen, the exception was raised while the code in the finally block was run.&nbsp;<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">In Summary,&nbsp;<\/h2>\n\n\n\n<p>You have seen the importance of exception handling in Python and how to do it. You learned about using the try, except, raise statement and how they function. Also, you discovered the various exceptions you have in Python. Although the code example here focused on ZeroDivisionError, it is pretty much the same process for other types of exceptions. If you have any questions, feel free to leave them in the comment section and I\u2019d do my best to answer them.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>An exception is a kind of error that occurs at runtime. Exceptions are different from errors as some of them can be dealt with without the program crashing. For instance, if you write a program to divide two numbers from a user. You must ensure that the denominator is not 0 as a number divided [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":8771,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[342],"tags":[],"class_list":["post-8766","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python-tutorials"],"_links":{"self":[{"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/posts\/8766","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/comments?post=8766"}],"version-history":[{"count":0,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/posts\/8766\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/media\/8771"}],"wp:attachment":[{"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/media?parent=8766"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/categories?post=8766"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/tags?post=8766"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}