{"id":25668,"date":"2021-12-04T09:19:07","date_gmt":"2021-12-04T03:49:07","guid":{"rendered":"https:\/\/python-programs.com\/?p=25668"},"modified":"2021-12-04T09:19:07","modified_gmt":"2021-12-04T03:49:07","slug":"exceptions-and-errors-in-python-different-exceptions-and-their-handling-in-python","status":"publish","type":"post","link":"https:\/\/python-programs.com\/exceptions-and-errors-in-python-different-exceptions-and-their-handling-in-python\/","title":{"rendered":"Exceptions and Errors\u00a0in Python – Different Exceptions and their Handling in Python"},"content":{"rendered":"

When we write a program, we can make mistakes that cause errors when we run it. When a Python program meets an unhandled error, it terminates. These errors can be divided into two categories:<\/p>\n

    \n
  1. Syntax Errors<\/li>\n
  2. Logical Errors(Exceptions)<\/li>\n<\/ol>\n

    Syntax Errors:<\/strong><\/p>\n

    Syntax error or parsing error refers to an error caused by not following the right structure (syntax) of the language.<\/p>\n

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

    numb = 10\r\nif(numb > 0)    # colon(:) is missing here \r\nprint(\"positive number\")\r\nelse:\r\n    print(\"Negative number\")\r\n<\/pre>\n

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

     File \"\/home\/ba12f4db06be8a7ce06b7796040d87d0.py\", line 2\r\n    if(numb > 0)\r\n               ^\r\nSyntaxError: invalid syntax<\/pre>\n

    An arrow in the example indicates where the parser encountered the syntax problem.<\/p>\n

    We can see that there is no colon: in the if statement in line 2<\/p>\n

    Logical Errors(Exceptions):<\/strong><\/p>\n

    Exceptions or logical errors are errors that occur at runtime (after passing the syntax test).<\/p>\n

    An exception is a condition in a program that interrupts the flow of the program and causes the code to stop running. Python has a fantastic approach to handling exceptions so that the code runs without problems or disruptions.<\/p>\n

    For example, they occur when we attempt to open (read) a file that does not exist (FileNotFoundError), divide an integer by zero (ZeroDivisionError), or import a module that does not exist (ImportError).<\/p>\n

    Python generates an exception object if these types of runtime issues occur. If the error is not handled appropriately, it prints a traceback to the error as well as some information about why the issue happened.<\/p>\n

    Exceptions can be either built-in errors\/exceptions or bespoke exceptions.<\/p>\n

    The following are some examples of common in-built exceptions:<\/p>\n