{"id":8356,"date":"2023-11-09T18:42:46","date_gmt":"2023-11-09T13:12:46","guid":{"rendered":"https:\/\/python-programs.com\/?p=8356"},"modified":"2023-11-10T12:24:26","modified_gmt":"2023-11-10T06:54:26","slug":"python-data-persistence-exceptions","status":"publish","type":"post","link":"https:\/\/python-programs.com\/python-data-persistence-exceptions\/","title":{"rendered":"Python Data Persistence – Exceptions"},"content":{"rendered":"

Python Data Persistence – Exceptions<\/h2>\n

Even an experienced programmer\u2019s code does contain errors. If errors pertain to violation of language syntax, more often than not, they are detected by the interpreter (compiler in case of C++\/Java) and code doesn\u2019t execute till they are corrected.<\/p>\n

There are times though when the code doesn\u2019t show syntax-related errors but errors creep up after running it. What is more, sometimes code might execute without errors and some other times, its execution abruptly terminates. Clearly, some situation that arises in a running code is not tolerable to the interpreter. Such a runtime situation causing the error is called an exception.
\nTake a simple example of displaying the result of two numbers input by the user. The following snippet appears error-free as far as syntax error is concerned.<\/p>\n

Example<\/strong><\/p>\n

num1=int(input('enter a number..')) \r\nnum2 = int(input(1 enter another number..')) \r\nresult=num1\/num2 \r\nprint ('result: ' , result)<\/pre>\n

When executed, above code gives satisfactory output on most occasions, but when num2 happens to be 0, it breaks, (figure 5.3)<\/p>\n

enter a number . . 12\r\nenter another number . . 3\r\nresult: 4.0\r\nenter a number . . 12\r\nenter another number . . 0\r\nTraceback (most recent call last) :\r\nFile \"E:\\python37\\tmp.py\", line 3, in <module> \r\nresult =num1\/num2\r\nZeroDivisionError: division by zero<\/pre>\n

You can see that the program terminates as soon as it encounters the error without completing the rest of the statements. Such abnormal termination may prove to be harmful in some cases.
\nImagine a situation involving a file object. If such runtime error occurs after the file is opened, the abrupt end of the program will not give a chance for the file object to close properly and it may result in corruption of data in the file. Hence exceptions need to be properly handled so that program ends safely.<\/p>\n

If we look at the class structure of builtins in Python, there is an Exception<\/strong> class from which a number of built-in exceptions are defined. Depending upon the cause of exception in a running program, the object representing the corresponding exception class is created. In this section, we restrict ourselves to consider file operations-related exceptions.<\/p>\n

Python\u2019s exception handling mechanism is implemented by the use of two keywords – try<\/strong> and except. Both keywords are followed by a block of statements. The try:<\/strong> block contains a piece of code that is likely to encounter an exception. The except<\/strong> block follows the try:<\/strong> block containing statements meant to handle the exception. The above code snippet of the division of two numbers is rewritten to use the try-catch mechanism.<\/p>\n

Example<\/strong><\/p>\n

try:\r\nnum1=int(input('enter a number..'))\r\nnum2=int(input('enter another number..'))\r\nresult=num1\/num2\r\nprint (' result: ' , result)\r\nexcept:\r\nprint (\"error in division\")\r\nprint (\"end of program\")<\/pre>\n

Now there are two possibilities. As said earlier, the exception is a runtime situation largely depending upon reasons outside the program. In the code involving the division of two numbers, there is no exception if the denominator is non-zero. In such a case, try: block is executed completely, except block is bypassed and the program proceeds to subsequent statements.<\/p>\n

If however, the denominator happens to be zero, a statement involving division produces an exception. Python interpreter abandons rest of statements in try: block and sends the program flow to except: block where exception handling statements are given. After except: block rest of unconditional statements keep on executing, (figure 5.4)<\/p>\n

enter a number..15 \r\nenter another number..5 \r\nresult: 3.0\r\nend of program \r\nenter a number..15 \r\nenter another number..0 \r\nerror in division \r\nend of program<\/pre>\n

Here, except block without any expression acts as a generic exception handler. To catch objects of a specific type of exception, the corresponding Exception class is mentioned in front of except keyword. In this case, ZeroDivisionError is raised, so it is mentioned in except statement. Also, you can use the \u2018as\u2019 keyword to receive the exception object in an argument and fetch more information about the exception.<\/p>\n

Example<\/strong><\/p>\n

try:\r\nnum1=int(input('enter a number..')) \r\nnum2=int(input('enter another number..')) \r\nresult =num1\/num2 \r\nprint ('result: ', result) \r\nexcept ZeroDivisionError as e: \r\nprint (\"error message\",e) \r\nprint (\"end of program\")<\/pre>\n

File operations are always prone to raising exceptions. What if the file you are trying to open doesn\u2019t exist at all? What if you opened a file in \u2018r\u2019 mode but trying to write data to it? These situations will raise runtime errors (exceptions) which must be handled using the try-except mechanism to avoid damage to data in files.
\nFileNotFoundError is a common exception encountered. It appears when an attempt to read a non-existing file. The following code handles the error.<\/p>\n

Example<\/strong><\/p>\n

E:\\python37>python tmp.py\r\nenter a filename, .testfile.txt\r\nH e l l o P y t h o n\r\nend of program\r\nE:\\python37>python tmp.py\r\nenter filename, .nofile.txt\r\nerror message [Errno 2] No such file or directory:\r\n' nofile . txt '\r\nend of program<\/pre>\n

Another exception occurs frequently when you try to write data in a file opened with \u2018r\u2019 mode. Type of exception is UnsupportedOperation defined in the io module.<\/p>\n

Example<\/strong><\/p>\n

import io\r\ntry:\r\nf=open ( ' testfile . txt1 , ' r ')\r\nf.write('Hello')\r\nprint (data)\r\nexcept io.UnsupportedOperation as e:\r\nprint (\"error message\",e)\r\nprint (\"end of program\")<\/pre>\n

Output<\/strong><\/p>\n

E:\\python37 >python tmp.py \r\nerror message not writable \r\nend of program<\/pre>\n

As we know, the write ( ) method of file objects needs a string argument. Hence the argument of any other type will result in typeError.<\/p>\n

Example<\/strong><\/p>\n

try:\r\nf=open (' testfile . txt' , ' w')\r\nf.write(1234)\r\nexcept TypeError as e:\r\nprint (\"error message\",e)\r\nprint (\"end of program\")<\/pre>\n

 <\/p>\n

Output<\/strong><\/p>\n

E:\\python37>python tmp.py\r\nerror message write() argument must be str, not int end of program<\/pre>\n

Conversely, for file in binary mode, the write ()<\/strong> method needs bytes object as argument. If not, same TypeError is raised with different error message.<\/p>\n

Example<\/strong><\/p>\n

try:\r\nf =open ( ' testfile . txt' , ' wb' )\r\nf.write('Hello1)\r\nexcept TypeError as e:\r\nprint (\"error message\",e)\r\nprint (\"end of program\")<\/pre>\n

Output<\/strong><\/p>\n

E:\\python37>python tmp.py\r\nerror message a bytes-like object is required, not 'str'\r\nend of program<\/pre>\n

All file-related functions in the os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type but are not accepted by the operating system.<\/p>\n

Example<\/strong><\/p>\n

import os\r\ntry:\r\nfd=os . open ( ' testfile . txt' , os . 0_RD0NLY | os . 0_CREAT) os.write(fd,'Hello'.encode())\r\nexcept OSError as e:\r\nprint (\"error message\",e)\r\nprint (\"end of program\")<\/pre>\n

Output<\/strong><\/p>\n

E:\\python37>python tmp.py\r\nerror message [Errno 9] Bad file descriptor \r\nend of program<\/pre>\n

In this chapter, we learned the basic file handling techniques. In the next chapter, we deal with advanced data serialization techniques and special-purpose file storage formats using Python\u2019s built-in modules.<\/p>\n","protected":false},"excerpt":{"rendered":"

Python Data Persistence – Exceptions Even an experienced programmer\u2019s code does contain errors. If errors pertain to violation of language syntax, more often than not, they are detected by the interpreter (compiler in case of C++\/Java) and code doesn\u2019t execute till they are corrected. There are times though when the code doesn\u2019t show syntax-related errors …<\/p>\n

Python Data Persistence – Exceptions<\/span> Read More »<\/a><\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"spay_email":"","jetpack_publicize_message":"","jetpack_is_tweetstorm":false,"jetpack_publicize_feature_enabled":true},"categories":[5],"tags":[],"yoast_head":"\nPython Data Persistence - Exceptions - Python Programs<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/python-programs.com\/python-data-persistence-exceptions\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Python Data Persistence - Exceptions - Python Programs\" \/>\n<meta property=\"og:description\" content=\"Python Data Persistence – Exceptions Even an experienced programmer\u2019s code does contain errors. If errors pertain to violation of language syntax, more often than not, they are detected by the interpreter (compiler in case of C++\/Java) and code doesn\u2019t execute till they are corrected. There are times though when the code doesn\u2019t show syntax-related errors … Python Data Persistence – Exceptions Read More »\" \/>\n<meta property=\"og:url\" content=\"https:\/\/python-programs.com\/python-data-persistence-exceptions\/\" \/>\n<meta property=\"og:site_name\" content=\"Python Programs\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/btechgeeks\" \/>\n<meta property=\"article:published_time\" content=\"2023-11-09T13:12:46+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-11-10T06:54:26+00:00\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@btech_geeks\" \/>\n<meta name=\"twitter:site\" content=\"@btech_geeks\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Prasanna\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"6 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Organization\",\"@id\":\"https:\/\/python-programs.com\/#organization\",\"name\":\"BTech Geeks\",\"url\":\"https:\/\/python-programs.com\/\",\"sameAs\":[\"https:\/\/www.instagram.com\/btechgeeks\/\",\"https:\/\/www.linkedin.com\/in\/btechgeeks\",\"https:\/\/in.pinterest.com\/btechgeek\/\",\"https:\/\/www.youtube.com\/channel\/UC9MlCqdJ3lKqz2p5114SDIg\",\"https:\/\/www.facebook.com\/btechgeeks\",\"https:\/\/twitter.com\/btech_geeks\"],\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/python-programs.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/python-programs.com\/wp-content\/uploads\/2020\/11\/BTechGeeks.png\",\"contentUrl\":\"https:\/\/python-programs.com\/wp-content\/uploads\/2020\/11\/BTechGeeks.png\",\"width\":350,\"height\":70,\"caption\":\"BTech Geeks\"},\"image\":{\"@id\":\"https:\/\/python-programs.com\/#\/schema\/logo\/image\/\"}},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/python-programs.com\/#website\",\"url\":\"https:\/\/python-programs.com\/\",\"name\":\"Python Programs\",\"description\":\"Python Programs with Examples, How To Guides on Python\",\"publisher\":{\"@id\":\"https:\/\/python-programs.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/python-programs.com\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/python-programs.com\/python-data-persistence-exceptions\/#webpage\",\"url\":\"https:\/\/python-programs.com\/python-data-persistence-exceptions\/\",\"name\":\"Python Data Persistence - Exceptions - Python Programs\",\"isPartOf\":{\"@id\":\"https:\/\/python-programs.com\/#website\"},\"datePublished\":\"2023-11-09T13:12:46+00:00\",\"dateModified\":\"2023-11-10T06:54:26+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/python-programs.com\/python-data-persistence-exceptions\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/python-programs.com\/python-data-persistence-exceptions\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/python-programs.com\/python-data-persistence-exceptions\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/python-programs.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Python Data Persistence – Exceptions\"}]},{\"@type\":\"Article\",\"@id\":\"https:\/\/python-programs.com\/python-data-persistence-exceptions\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/python-programs.com\/python-data-persistence-exceptions\/#webpage\"},\"author\":{\"@id\":\"https:\/\/python-programs.com\/#\/schema\/person\/ea8ce699662f0d7e248e52fe080b85bb\"},\"headline\":\"Python Data Persistence – Exceptions\",\"datePublished\":\"2023-11-09T13:12:46+00:00\",\"dateModified\":\"2023-11-10T06:54:26+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/python-programs.com\/python-data-persistence-exceptions\/#webpage\"},\"wordCount\":789,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/python-programs.com\/#organization\"},\"articleSection\":[\"Python\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/python-programs.com\/python-data-persistence-exceptions\/#respond\"]}]},{\"@type\":\"Person\",\"@id\":\"https:\/\/python-programs.com\/#\/schema\/person\/ea8ce699662f0d7e248e52fe080b85bb\",\"name\":\"Prasanna\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/python-programs.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/174540ad43736c7d1a4c4f83c775e74d?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/174540ad43736c7d1a4c4f83c775e74d?s=96&d=mm&r=g\",\"caption\":\"Prasanna\"},\"url\":\"https:\/\/python-programs.com\/author\/prasanna\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Python Data Persistence - Exceptions - Python Programs","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/python-programs.com\/python-data-persistence-exceptions\/","og_locale":"en_US","og_type":"article","og_title":"Python Data Persistence - Exceptions - Python Programs","og_description":"Python Data Persistence – Exceptions Even an experienced programmer\u2019s code does contain errors. If errors pertain to violation of language syntax, more often than not, they are detected by the interpreter (compiler in case of C++\/Java) and code doesn\u2019t execute till they are corrected. There are times though when the code doesn\u2019t show syntax-related errors … Python Data Persistence – Exceptions Read More »","og_url":"https:\/\/python-programs.com\/python-data-persistence-exceptions\/","og_site_name":"Python Programs","article_publisher":"https:\/\/www.facebook.com\/btechgeeks","article_published_time":"2023-11-09T13:12:46+00:00","article_modified_time":"2023-11-10T06:54:26+00:00","twitter_card":"summary_large_image","twitter_creator":"@btech_geeks","twitter_site":"@btech_geeks","twitter_misc":{"Written by":"Prasanna","Est. reading time":"6 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Organization","@id":"https:\/\/python-programs.com\/#organization","name":"BTech Geeks","url":"https:\/\/python-programs.com\/","sameAs":["https:\/\/www.instagram.com\/btechgeeks\/","https:\/\/www.linkedin.com\/in\/btechgeeks","https:\/\/in.pinterest.com\/btechgeek\/","https:\/\/www.youtube.com\/channel\/UC9MlCqdJ3lKqz2p5114SDIg","https:\/\/www.facebook.com\/btechgeeks","https:\/\/twitter.com\/btech_geeks"],"logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/python-programs.com\/#\/schema\/logo\/image\/","url":"https:\/\/python-programs.com\/wp-content\/uploads\/2020\/11\/BTechGeeks.png","contentUrl":"https:\/\/python-programs.com\/wp-content\/uploads\/2020\/11\/BTechGeeks.png","width":350,"height":70,"caption":"BTech Geeks"},"image":{"@id":"https:\/\/python-programs.com\/#\/schema\/logo\/image\/"}},{"@type":"WebSite","@id":"https:\/\/python-programs.com\/#website","url":"https:\/\/python-programs.com\/","name":"Python Programs","description":"Python Programs with Examples, How To Guides on Python","publisher":{"@id":"https:\/\/python-programs.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/python-programs.com\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/python-programs.com\/python-data-persistence-exceptions\/#webpage","url":"https:\/\/python-programs.com\/python-data-persistence-exceptions\/","name":"Python Data Persistence - Exceptions - Python Programs","isPartOf":{"@id":"https:\/\/python-programs.com\/#website"},"datePublished":"2023-11-09T13:12:46+00:00","dateModified":"2023-11-10T06:54:26+00:00","breadcrumb":{"@id":"https:\/\/python-programs.com\/python-data-persistence-exceptions\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/python-programs.com\/python-data-persistence-exceptions\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/python-programs.com\/python-data-persistence-exceptions\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/python-programs.com\/"},{"@type":"ListItem","position":2,"name":"Python Data Persistence – Exceptions"}]},{"@type":"Article","@id":"https:\/\/python-programs.com\/python-data-persistence-exceptions\/#article","isPartOf":{"@id":"https:\/\/python-programs.com\/python-data-persistence-exceptions\/#webpage"},"author":{"@id":"https:\/\/python-programs.com\/#\/schema\/person\/ea8ce699662f0d7e248e52fe080b85bb"},"headline":"Python Data Persistence – Exceptions","datePublished":"2023-11-09T13:12:46+00:00","dateModified":"2023-11-10T06:54:26+00:00","mainEntityOfPage":{"@id":"https:\/\/python-programs.com\/python-data-persistence-exceptions\/#webpage"},"wordCount":789,"commentCount":0,"publisher":{"@id":"https:\/\/python-programs.com\/#organization"},"articleSection":["Python"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/python-programs.com\/python-data-persistence-exceptions\/#respond"]}]},{"@type":"Person","@id":"https:\/\/python-programs.com\/#\/schema\/person\/ea8ce699662f0d7e248e52fe080b85bb","name":"Prasanna","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/python-programs.com\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/174540ad43736c7d1a4c4f83c775e74d?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/174540ad43736c7d1a4c4f83c775e74d?s=96&d=mm&r=g","caption":"Prasanna"},"url":"https:\/\/python-programs.com\/author\/prasanna\/"}]}},"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/posts\/8356"}],"collection":[{"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/comments?post=8356"}],"version-history":[{"count":3,"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/posts\/8356\/revisions"}],"predecessor-version":[{"id":9413,"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/posts\/8356\/revisions\/9413"}],"wp:attachment":[{"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/media?parent=8356"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/categories?post=8356"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/python-programs.com\/wp-json\/wp\/v2\/tags?post=8356"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}