{"id":3132,"date":"2021-04-20T15:04:40","date_gmt":"2021-04-20T09:34:40","guid":{"rendered":"https:\/\/python-programs.com\/?p=3132"},"modified":"2021-11-22T18:39:23","modified_gmt":"2021-11-22T13:09:23","slug":"python-programming-exceptions","status":"publish","type":"post","link":"https:\/\/python-programs.com\/python-programming-exceptions\/","title":{"rendered":"Python Programming \u2013 Exceptions"},"content":{"rendered":"

In this Page, We are Providing Python Programming \u2013 Exceptions. Students can visit for more Detail and Explanation of Python Handwritten Notes<\/a>\u00a0Pdf.<\/p>\n

Python Programming \u2013 Exceptions<\/h2>\n

Exceptions<\/strong><\/p>\n

The exception is a way of breaking out of the normal flow of control of a code block in order to handle the error or other exceptional conditions. An exception is raised at the point where the error is detected.<\/p>\n

>>> while True print ' Hello world '\r\nSyntaxError: invalid syntax \r\n>>> 10 \/ 0\r\n\r\nTraceback (most recent call last) : \r\nFile \"<pyshell#l>\", line 1, in <module>\r\n\u00a0 \u00a0 10 \/ 0 \r\nZeroDivisionError: integer division or modulo by zero \r\n>>> 4+tt*3\r\n\r\nTraceback (most recent call last) :\r\nFile \"<pyshe11#2>\", line 1, in <module>\r\n4+tt*3\r\nNameError: name ' tt ' is not defined \r\n>>> ' 5 '+7\r\n\r\nTraceback (most recent call last) :\r\nFile \"<pyshe11#3>\", line 1, in <module>\r\n' 5 '+7\r\nTypeError: cannot concatenate ' str ' and ' int ' objects<\/pre>\n

The last line of the error message indicates what went wrong. Exceptions are of different types, and the type is printed as part of the message; the types in the above example are SyntaxError, ZeroDivisionError, NameError, and TypeError. Standard exception names are built-in identifiers (not reserved keywords). The rest of the lines provides detail based on the type of exception and what caused it.<\/p>\n

Handling exceptions<\/strong><\/p>\n

If there is some suspicious code that may raise an exception, it can be handled by placing the suspicious code in a try compound statement. After the try clause, include an except clause, followed by a block of code that handles the problem. The following example attempts to open a file and write something in the file.<\/p>\n

# ! \/ usr \/ bin \/ python \r\ntry :\r\n\u00a0 \u00a0 \u00a0fh = open ( \" testflie \" , \" w \" )\r\n\u00a0 \u00a0 \u00a0fh.write ( \" This is my test file for exception handling ! ! \" ) \r\nexcept IOError :\r\nprint \" Error: can\\'t find the file or read data \" \r\nelse: \r\nprint \" Written content in the file successfully \" \r\nfh.close ( )<\/pre>\n

Here are few important points that need to be remembered:<\/p>\n