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.
Python a = 10000 if a > 2999 print("Eligible")
Output
Syntax errorExample 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.
Python
Output
Syntax errorPython 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:
Python a = [10, 20, 30, 40, 50] b = 0 for i in a: b += i res = b / len(a) - 1 print(res)
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.
Python try: print("code start") print(1 / 0) except: print("an error occurs") finally: print("GeeksForGeeks")
Outputcode 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.
Python try: a = 1999 if a < 2999: raise ValueError("please add money") else: print("Eligible") except ValueError as e: print(e)
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
Python Built-in Exceptions In Python, exceptions are events that can alter the flow of control in a program. These errors can arise during program execution and need to be handled appropriately. Python provides a set of built-in exceptions, each meant to signal a particular type of error.We can catch exceptions using try and
8 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 sy
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:Pythonn = int(input(
4 min read