Love our work? Support Us

30 Python Errors and Exceptions: How to Fix Them

A Python Error is an issue that occurs when a program written in the Python programming language does not run as expected due to syntax or logical errors. Syntax errors occur when the program does not follow the correct rules of the language, such as forgetting to close a quotation mark or using a keyword incorrectly.


Logical errors occur when the programmer has not written the code correctly to achieve the desired outcome, such as using the wrong comparison operator or referencing an undefined variable. Python Errors are usually reported with an error message that identifies the line in the code that caused the problem.


A Python Exception is an error that occurs during the execution of a program. It is usually caused by a syntax error or an issue with the program's logic. Exceptions can be handled in Python by using try and except statements, which allow the program to continue running despite the exception. It is important to note that an exception should be handled appropriately so that the program can continue to run correctly.


There is a difference between a Python Exception and a Python error. A Python error is an indication that something is wrong with the code, such as a syntax error, or an issue with the arguments passed to a function. An exception is a special type of error that is Occurs by Python when an operation fails, such as an attempt to divide by zero or accessing a nonexistent object. Exceptions are handled differently than errors, and can be caught and handled with try/except blocks.


In this post, we explain the 30 Python errors and exceptions, their causes, and how to fix them.

Python Errors and Exceptions Overview


Python Errors are issues that arise when incorrect syntax or incorrect code is written. They can be syntax errors, runtime errors, logical errors, and exceptions. Syntax errors are caused by typos or incorrect indentation, runtime errors are caused by incorrect logic, and logical errors are caused by incorrect assumptions. Exceptions are errors detected during execution of the program.


Python exceptions are errors that occur during the execution of a program. They are Occurs when a program encounters an error condition such as an invalid input, division by zero, or a missing file. Exceptions can be handled with try/except statements to avoid disrupting the normal flow of the program. Custom exceptions can also be created to provide meaningful error messages to the user.


Note that there is a difference between a Python error and Python exception. We will see this difference with example in the next part.


What is Errors and Exceptions in Python?


Errors and Exceptions in Python are conditions that interrupt the normal flow of a program. They can be handled and dealt with in order to continue the program.


What is Errors in Python?


We have seen above that Python errors are problems that occur when incorrect syntax is used, or when a program is unable to run due to an unexpected condition. They are often identified by messages such as "SyntaxError", "TypeError", "NameError" and "ValueError".


Let us use the example below.


Example1:


On the page of the free online compiler for different programming languages(PL), we get.


PythonErrors1


This Python code will raise SyntaxError as shown in the above image becausse the print is a Python built in that it must end with a closing bracket.


Let us see another example.


Example2:


The free online compiler by mcqsmonitor for different programming languages(PL) help us to get:


PythonErrors


We will see how to fix this python error later on this page. The error is caused by the ";" instead of ",".


What is Exceptions in Python?


We have seen also in above section that Python exceptions are errors which occur during the execution of a program, and are generally caused by invalid input or code. They are handled using try-except blocks, which allow the program to continue running after encountering an error, rather than crashing.


In order to better understand the Python exceptions, we need to use the examples.


Example3:


We get the following error message in the output.


PythonErrors1


This Python code will raise ValueError as shown in the above image becausse the square root needs a positive number as input.


Another example of Python Exception is ZeroDivisionError.


Example4:


The free online compiler by mcqsmonitor for different programming languages(PL) help us to get:


PythonErrors


We obtain the Python exception since the division by zero is not possible in Mathematics.


What Causes Python Errors and Exceptions


The causes of Python errors and exceptions are vast depending on the error or exception. Here, we want to list some of the causes below:


What Causes Python Errors


  1. Syntax Error: This occurs when the programmer does not follow the proper syntax of Python while coding.

  2. Indentation Error: This occurs when the programmer does not use proper indentation while coding.

  3. Runtime Error: This occurs when the code is syntactically correct but the program encounters some unexpected inputs or conditions.

  4. NameError: This occurs when the programmer attempts to use a variable that has not been defined.

What Causes Python Exceptions


  1. ImportError: Occurs when a module or a package cannot be found.

  2. AttributeError: Occurs when a variable does not have an attribute.

  3. KeyError: Occurs when a dictionary does not have a specific key.

  4. IndexError: Occurs when trying to access an element from a sequence (list, string, tuple, etc.) which is out of range.

Now that we have seen some examples of causes of Python errors and exceptions, we want to see how to fix each one.

How to Fix Errors and Exception in Python


The ways Python errors are fixed are different from the ways Python exceptions are handled.


How to Fix Errors in Python


Let us come back to the above example on Python errors and fixed those examples.


We start with the first example.


Example5:


We obtain the following output without Python error.


PythonErrors1


Let us see another example fixed.


Example6:


The free online compiler by mcqsmonitor for different programming languages(PL) help us to get:


PythonErrors


How to Fix Exceptions in Python


Here, we can fix the exceptions in Python by using try/except block statement.


We start with the first example.


Example7:


We obtain the following output displaying why the square root is not obtained. Here the Python error is hiden using the try/except.


PythonErrors1


Let us see another example of Python exception fixed.


Example8:


We can use this free online compiler by mcqsmonitor for different programming languages(PL) help us to get:


PythonErrors


30 Python Errors and Exceptions: How to Fix Them


We have made a list of 30 Python Errors and Exceptions and how to fix them in the following table.


No Error/Exception Cause of error/exception How to Fix
1 Python AssertionError Occurs when an assert statement fails. How to fix the Python AssertionError
2 Python AttributeError Occurs when attribute assignment or reference fails. How to fix the Python AssertionError
3 Python EOFError Occurs when the input() function hits end-of-file condition How to fix the Python EOFError
4 Python FloatingPointError Appears when a floating point operation fails. How to fix the Python FloatingPointError
5 Python GeneratorExit Appears when a generator's close() method is called. Catch the GeneratorExit exception and call the generator's close method.
6 Python ImportError Occurs when the imported module or class is not found. How to fix the Python ImportError
7 Python IndexError Appears when the index of a sequence is out of range. How to fix the Python IndexError
8 Python KeyError Occurs when a key is not found in a dictionary. How to fix the Python KeyError
9 Python KeyboardInterrupt Appears when the user hits the interrupt key (Ctrl+C or Delete). Press Ctrl+C to stop the program and interrupt the keyboard.
10 Python MemoryError Occurs when an operation runs out of memory. How to fix the Python MemoryError
11 Python NameError Appears when a variable is not found in local or global scope. How to fix the Python NameError
12 Python NotImplementedError Occurs by abstract methods. Implement the function or replace it with an appropriate implementation.
13 Python OSError Occurs when system operation causes system related error. Check if file path is valid, and if not, provide a valid one.
14 Python OverflowError Appears when the result of an arithmetic operation is too large to be represented. How to fix the Python OverflowError
15 Python ReferenceError Occurs when a weak reference proxy is used to access a garbage collected referent. Check the syntax of your code and ensure all variables are properly defined.
16 Python RuntimeError Occurs when an error does not fall under any other category. How to fix the Python RuntimeError
17 Python StopIteration Occurs by next() function to indicate that there is no further item to be returned by iterator. How to fix the Python Stopiteration
18 Python SyntaxError Occurs by parser when syntax error is encountered. How to fix the Python SyntaxError
19 Python IndentationError Occurs when there is incorrect indentation. How to fix the Python IndentationError
20 Python TabError Occurs when indentation consists of inconsistent tabs and spaces. How to fix the Python TabError
21 Python SystemError Occurs when interpreter detects internal error. Reinstall Python or repair the corrupted files.
22 Python SystemExit Occurs by sys.exit() function. Change the code to avoid raising SystemExit.
23 Python TypeError Occurs when a function or operation is applied to an object of incorrect type. How to fix the Python TypeError
24 Python UnboundLocalError Occurs when a reference is made to a local variable in a function or method, but no value has been bound to that variable. Rename variables so they don't conflict with global ones.
25 Python UnicodeError Occurs when a Unicode-related encoding or decoding error occurs. Ensure your program is using the correct encoding type for the text.
26 Python UnicodeEncodeError Occurs when a Unicode-related error occurs during encoding. Set the encoding when writing/reading files to avoid the error.
27 Python UnicodeDecodeError Occurs when a Unicode-related error occurs during decoding. Use the "encoding" parameter when opening files to specify the correct encoding.
28 Python UnicodeTranslateError Occurs when a Unicode-related error occurs during translating. Replace the problematic characters with valid ones, or use the "ignore" option when decoding.
29 Python ValueError Occurs when a function gets an argument of correct type but improper value. How to fix the Python ValueError
30 Python ZeroDivisionError Occurs when the second operand of division or modulo operation is zero. How to fix the Python ZeroDivisionError

Conclusion


Python Errors and Python Exceptions are objects representing errors that occur during the execution of a program. These objects are raised when an error occurs, and can be handled by the programmer to customize the response to the error. Common errors include SyntaxError, NameError, TypeError and ValueError. Exceptions are errors that can be handled, such as IOError, KeyboardInterrupt, and ZeroDivisionError, and are used to indicate that an unexpected situation has occurred in the program. Exceptions can be caught and handled with the try-except block, allowing the programmer to respond to errors in a controlled manner.


March 26, 2023 . By mcqsmonitor Editorial Team