Errors and Exceptions in Python
Last Updated :
26 Apr, 2025
Errors are problems in a program that causes the program to stop its execution. On the other hand, exceptions are raised when some internal events change the program’s normal flow.
Syntax Errors in Python
Syntax error occurs when the code doesn’t follow Python’s rules, like using incorrect grammar in English. Python stops and points out the issue before running the program.
Example 1 : In this example, this code returns a syntax error because there is a missing colon (:) after the if statement. The correct syntax requires a colon to indicate the start of the block of code to be executed if the condition is true.
[GFGTABS]
Python
a = 10000
if a > 2999
print("Eligible")
[/GFGTABS]
Output

Syntax error
Example 2: This code returns a syntax error because parentheses around the condition in an if statement are not required in Python. While optional, their unnecessary use can lead to incorrect syntax.
[GFGTABS]
Python
[/GFGTABS]
Output

Syntax error
Python Logical Errors (Exception)
Logical errors are subtle bugs in the program that allow the code to run, but produce incorrect or unintended results. These are often harder to detect since the program doesn’t crash, but the output is not as expected.
Characteristics of Logical Errors
- No Syntax Error: The code runs without issues.
- Unexpected Output: The results produced by the program are not what the programmer intended.
- Difficult to Detect: These errors can be tricky to spot since there’s no obvious problem with the code itself.
- Causes: Faulty logic, incorrect assumptions, or improper use of operators.
Example:
[GFGTABS]
Python
a = [10, 20, 30, 40, 50]
b = 0
for i in a:
b += i
res = b / len(a) - 1
print(res)
[/GFGTABS]
Explanation: Expected output is that the average of a should be 30, but the program outputs 29.0. The logical error occurs because the formula b/ len(a) – 1 incorrectly subtracts 1, leading to an incorrect result. The correct formula should be b / len(a).
Common Builtin Exceptions
Some of the common built-in exceptions are other than above mention exceptions are:
Exception |
Description |
IndexError |
When the wrong index of a list is retrieved. |
AssertionError |
It occurs when the assert statement fails |
AttributeError |
It occurs when an attribute assignment is failed. |
ImportError |
It occurs when an imported module is not found. |
KeyError |
It occurs when the key of the dictionary is not found. |
NameError |
It occurs when the variable is not defined. |
MemoryError |
It occurs when a program runs out of memory. |
TypeError |
It occurs when a function and operation are applied in an incorrect type. |
Note: For more information, refer to Built-in Exceptions in Python
Error Handling
Python provides mechanisms to handle errors and exceptions using the try, except, and finally blocks. This allows for graceful handling of errors without crashing the program.
Example 1: This example shows how try, except and finally handle errors. try runs risky code, except catches errors and finally runs always.
[GFGTABS]
Python
try:
print("code start")
print(1 / 0)
except:
print("an error occurs")
finally:
print("GeeksForGeeks")
[/GFGTABS]
Output
code start
an error occurs
GeeksForGeeks
Explanation:
- try block runs code, raising an exception if any occurs (e.g., 1 / 0 raises ZeroDivisionError).
- except block catches exceptions, printing “an error occurs” in case of an error.
- finally block always executes, printing “GeeksForGeeks” to signal the end of execution.
Example 2: This example shows how try and except handle custom errors. try checks a condition, raises a ValueError if it fails and except catches and prints the error message.
[GFGTABS]
Python
try:
a = 1999
if a < 2999:
raise ValueError("please add money")
else:
print("Eligible")
except ValueError as e:
print(e)
[/GFGTABS]
Explanation:
- try block sets a = 1999 raises a ValueError if a < 2999, otherwise prints “Eligible”.
- except block catches the ValueError and prints “please add money”.
Similar Reads
EnvironmentError Exception in Python
EnvironmentError is the base class for errors that come from outside of Python (the operating system, file system, etc.). It is the parent class for IOError and OSError exceptions. exception IOError - It is raised when an I/O operation (when a method of a file object ) fails. e.g "File not found" or
1 min read
Concrete Exceptions in Python
In Python, exceptions are a way of handling errors that occur during the execution of the program. When an error occurs Python raises an exception that can be caught and handled by the programmer to prevent the program from crashing. In this article, we will see about concrete exceptions in Python i
3 min read
Try, Except, else and Finally in Python
An Exception is an Unexpected Event, which occurs during the execution of the program. It is also known as a run time error. When that error occurs, Python generates an exception during the execution and that can be handled, which prevents your program from interrupting. Example: In this code, The s
6 min read
Handling EOFError Exception in Python
In Python, an EOFError is raised when one of the built-in functions, such as input() or raw_input() reaches the end-of-file (EOF) condition without reading any data. This commonly occurs in online IDEs or when reading from a file where there is no more data left to read. Example: [GFGTABS] Python n
4 min read
Python Print Exception
In Python, exceptions are errors that occur at runtime and can crash your program if not handled. While catching exceptions is important, printing them helps us understand what went wrong and where. In this article, we'll focus on different ways to print exceptions. Using as keywordas keyword lets u
3 min read
Define Custom Exceptions in Python
In Python, exceptions occur during the execution of a program that disrupts the normal flow of the programâs instructions. When an error occurs, Python raises an exception, which can be caught and handled using try and except blocks. Hereâs a simple example of handling a built-in exception: [GFGTABS
3 min read
Exception Groups in Python
In this article, we will see how we can use the latest feature of Python 3.11, Exception Groups. To use ExceptionGroup you must be familiar with Exception Handling in Python. As the name itself suggests, it is a collection/group of different kinds of Exception. Without creating Multiple Exceptions w
4 min read
Python - Catch All Exceptions
In this article, we will discuss how to catch all exceptions in Python using try, except statements with the help of proper examples. But before let's see different types of errors in Python. There are generally two types of errors in Python i.e. Syntax error and Exceptions. Let's see the difference
3 min read
Create an Exception Logging Decorator in Python
Prerequisites: Decorators in Python, Logging in Python Logging helps you to keep track of the program/application you run. It stores the outputs/errors/messages/exceptions anything you want to store. Program executions can be debugged with the help of print statements during the runtime of code. But
2 min read
Python Exception Handling
Python Exception Handling handles errors that occur during the execution of a program. Exception handling allows to respond to the error, instead of crashing the running program. It enables you to catch and manage errors, making your code more robust and user-friendly. Let's look at an example: Hand
7 min read