The Wayback Machine - https://web.archive.org/web/20241117211118/https://www.geeksforgeeks.org/errors-and-exceptions-in-python/
Open In App

Errors and Exceptions in Python

Last Updated : 25 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

When the proper syntax of the language is not followed then a syntax error is thrown.

Example: It returns a syntax error message because after the if statement a colon: is missing. We can fix this by writing the correct syntax.

Python3
# initialize the amount variable
amount = 10000

# check that You are eligible to
#  purchase Dsa Self Paced or not
if(amount>2999)
    print("You are eligible to purchase Dsa Self Paced")
    

Output:

Example 2: When indentation is not correct.  

Python
if(a<3):
print("gfg")

Output

Python Logical Errors (Exception)

A logical error in Python, or in any programming language, is a type of bug that occurs when a program runs without crashing but produces incorrect or unintended results. Logical errors are mistakes in the program’s logic that lead to incorrect behavior or output, despite the syntax being correct.

Characteristics of Logical Errors

  1. No Syntax Error: The code runs successfully without any syntax errors.
  2. Unexpected Output: The program produces output that is different from what is expected.
  3. Difficult to Detect: Logical errors can be subtle and are often harder to identify and fix compared to syntax errors because the program appears to run correctly.
  4. Varied Causes: They can arise from incorrect assumptions, faulty logic, improper use of operators, or incorrect sequence of instructions.

Example of a Logical Error

Consider a simple example where we want to compute the average of a list of numbers:

Python
numbers = [10, 20, 30, 40, 50]
total = 0

# Calculate the sum of the numbers
for number in numbers:
    total += number

# Calculate the average (this has a logical error)
average = total / len(numbers) - 1

print("The average is:", average)

Analysis

  • Expected Output: The average of the numbers [10, 20, 30, 40, 50] should be 30.
  • Actual Output: The program will output The average is: 29.0.

Cause of Logical Error

The logical error is in the calculation of the average:

average = total / len(numbers) - 1

Instead, it should be:

average = total / len(numbers)

The incorrect logic here is the subtraction of 1, which results in a wrong average calculation.

Common Builtin Exceptions

Some of the common built-in exceptions are other than above mention exceptions are:

ExceptionDescription
IndexErrorWhen the wrong index of a list is retrieved.
AssertionErrorIt occurs when the assert statement fails
AttributeErrorIt occurs when an attribute assignment is failed.
ImportErrorIt occurs when an imported module is not found.
KeyErrorIt occurs when the key of the dictionary is not found.
NameErrorIt occurs when the variable is not defined.
MemoryErrorIt occurs when a program runs out of memory.
TypeErrorIt 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

When an error and an exception are raised then we handle that with the help of the Handling method.

Handling Exceptions with Try/Except/Finally 

We can handle errors by the Try/Except/Finally method. we write unsafe code in the try, fall back code in except and final code in finally block.

Python
# put unsafe operation in try block
try:
    print("code start")

    # unsafe operation perform
    print(1 / 0)

# if error occur the it goes in except block
except:
    print("an error occurs")

# final code in finally block
finally:
    print("GeeksForGeeks")

Output:  

code start
an error occurs
GeeksForGeeks

Raising exceptions for a predefined condition 

When we want to code for the limitation of certain conditions then we can raise an exception. 

Python3
# try for unsafe code
try:
    amount = 1999
    if amount < 2999:
        
        # raise the ValueError
        raise ValueError("please add money in your account")
    else:
        print("You are eligible to purchase DSA Self Paced course")
            
# if false then raise the value error
except ValueError as e:
        print(e)

Output:

please add money in your account


Similar Reads

Python | Catching and Creating Exceptions
Catching all exceptions is sometimes used as a crutch by programmers who can’t remember all of the possible exceptions that might occur in complicated operations. As such, it is also a very good way to write undebuggable code. Because of this, if one catches all exceptions, it is absolutely critical to log or reports the actual reason for the excep
2 min read
User-defined Exceptions in Python with Examples
Prerequisite: This article is an extension to Exception Handling. In this article, we will try to cover How to Define Custom Exceptions in Python with Examples. Example: class CustomError(Exception): pass raise CustomError("Example of Custom Exceptions in Python") Output: CustomError: Example of Custom Exceptions in Python Python throws errors and
4 min read
Exceptions - Selenium Python
Exceptions in Selenium Python are the errors that occur when one of method fails or an unexpected event occurs. All instances in Python must be instances of a class that derives from BaseException. Two exception classes that are not related via subclassing are never equivalent, even if they have the same name. The built-in exceptions can be generat
3 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 between them. Difference between Syntax Error and
3 min read
How To Fix Valueerror Exceptions In Python
Python comes with built-in exceptions that are raised when common errors occur. These predefined exceptions provide an advantage because you can use the try-except block in Python to handle them beforehand. For instance, you can utilize the try-except block to manage the ValueError exception in Python. In this article, we will see some methods and
4 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 in detail with the help of examples. Concrete Excep
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] Python try: result = 10 / 0 except ZeroDivisionE
3 min read
How to Catch Multiple Exceptions in One Line in Python?
There might be cases when we need to have exceptions in a single line. In this article, we will learn about how we can have multiple exceptions in a single line. We use this method to make code more readable and less complex. Also, it will help us follow the DRY (Don't repeat code) code method. Generally to handle exceptions we use try/Except metho
2 min read
Scrapy - Exceptions
Python-based Scrapy is a robust and adaptable web scraping platform. It provides a variety of tools for systematic, effective data extraction from websites. It helps us to automate data extraction from numerous websites. Scrapy Python Scrapy describes the spider that browses websites and gathers data in a clear and concise manner. The spider is in
7 min read
How to fix 'django.core.exceptions.FieldDoesNotExist'
In this article we will explore how we can fix / solve the django.core.exceptions.FieldDoesNotExist' error This exception raised by Django indicates that the field we are trying to access or modify is not exist. There may be some typo mistakes, field may not be there. So in this article we are looking for the solutions to fix this error. What is 'd
4 min read
How to fix - django.core.exceptions.ImproperlyConfigured
In this article, we will explore how to resolve the `django.core.exceptions.ImproperlyConfigured` error in Django. We'll discuss possible solutions and approaches for handling this error, providing a thorough explanation along with examples. What is 'django.core.exceptions.ImproperlyConfigured'?`django.core.exceptions.ImproperlyConfigured` is an ex
4 min read
How to check whether a file exists without exceptions?
When working with files in Python, it’s often necessary to check if a file exists before attempting to read from or write to it. While exception handling using try and except blocks is a common approach, Python provides cleaner and more intuitive methods to achieve this. In this article, we will explore various ways to check for file existence with
2 min read
Python Flask - Redirect and Errors
We'll discuss redirects and errors with Python Flask in this article. A redirect is used in the Flask class to send the user to a particular URL with the status code. conversely, this status code additionally identifies the issue. When we access a website, our browser sends a request to the server, and the server replies with what is known as the H
4 min read
Auto Search StackOverflow for Errors in Code using Python
Ever faced great difficulty in copying the error you're stuck with, opening the browser, pasting it, and opening the right Stack Overflow Answer? Worry Not, Here's the solution! What we are going to do is to write a Python script, which automatically detects the error from code, search about it on Stack Overflow, and opens up the few tabs related t
3 min read
JSON Parsing Errors in Python
JSON is a widely used format for exchanging data between systems and applications. Python provides built-in support for working with JSON data through its JSON module. However, JSON parsing errors can occur due to various reasons such as incorrect formatting, missing data, or data type mismatches. There are different JSON parsing errors that can oc
6 min read
How to Handle 'psycopg2.errors.invaliddatetimeformat' Error in Python
The psycopg2 library is a popular PostgreSQL database adapter for Python. While working with databases, it's common to encounter various types of errors. One such error is psycopg2.errors.InvalidDatetimeFormat. This article will delve into what causes the psycopg2.errors.InvalidDatetimeFormat error and provide practical solutions with correct code
3 min read
How to Fix 'psycopg2.errors.insufficientprivilege' in Python
When working with PostgreSQL databases in Python using the psycopg2 library, you might encounter the error psycopg2.errors.insufficientprivilege: permission denied for schema public. This error typically arises when a user attempts to perform an operation without the necessary permissions on the specified schema, in this case, the public schema. Un
4 min read
Django - Convert form.errors to Python Dictionary
When working with Django forms, handling and displaying form validation errors efficiently is crucial for building user-friendly web applications. The form.errors attribute in Django provides error messages generated when a form is invalid. By default, form.errors returns an instance of ErrorDict, which is a specialized dictionary-like object. But
4 min read
Logging Server Errors in Django
When building web applications, logging is an essential tool for developers to monitor the application’s health, diagnose issues, and understand user behavior. Django provides robust logging capabilities allowing us to capture, track, and handle server errors effectively. This article will walk you through the process of setting up and managing log
6 min read
Important differences between Python 2.x and Python 3.x with examples
In this article, we will see some important differences between Python 2.x and Python 3.x with the help of some examples. Differences between Python 2.x and Python 3.x Here, we will see the differences in the following libraries and modules: Division operatorprint functionUnicodexrangeError Handling_future_ modulePython Division operatorIf we are p
5 min read
Creating and updating PowerPoint Presentations in Python using python - pptx
python-pptx is library used to create/edit a PowerPoint (.pptx) files. This won't work on MS office 2003 and previous versions. We can add shapes, paragraphs, texts and slides and much more thing using this library. Installation: Open the command prompt on your system and write given below command: pip install python-pptx Let's see some of its usag
4 min read
Learn DSA with Python | Python Data Structures and Algorithms
This tutorial is a beginner-friendly guide for learning data structures and algorithms using Python. In this article, we will discuss the in-built data structures such as lists, tuples, dictionaries, etc, and some user-defined data structures such as linked lists, trees, graphs, etc, and traversal as well as searching and sorting algorithms with th
15+ min read
Setting up ROS with Python 3 and Python OpenCV
Setting up a Robot Operating System (ROS) with Python 3 and OpenCV can be a powerful combination for robotics development, enabling you to leverage ROS's robotics middleware with the flexibility and ease of Python programming language along with the computer vision capabilities provided by OpenCV. Here's a step-by-step guide to help you set up ROS
3 min read
Reading Python File-Like Objects from C | Python
Writing C extension code that consumes data from any Python file-like object (e.g., normal files, StringIO objects, etc.). read() method has to be repeatedly invoke to consume data on a file-like object and take steps to properly decode the resulting data. Given below is a C extension function that merely consumes all of the data on a file-like obj
3 min read
Python | Add Logging to a Python Script
In this article, we will learn how to have scripts and simple programs to write diagnostic information to log files. Code #1 : Using the logging module to add logging to a simple program import logging def main(): # Configure the logging system logging.basicConfig(filename ='app.log', level = logging.ERROR) # Variables (to make the calls that follo
2 min read
Python | Add Logging to Python Libraries
In this article, we will learn how to add a logging capability to a library, but don’t want it to interfere with programs that don’t use logging. For libraries that want to perform logging, create a dedicated logger object, and initially configure it as shown in the code below - Code #1 : C/C++ Code # abc.py import logging log = logging.getLogger(_
2 min read
Python | Index of Non-Zero elements in Python list
Sometimes, while working with python list, we can have a problem in which we need to find positions of all the integers other than 0. This can have application in day-day programming or competitive programming. Let's discuss a shorthand by which we can perform this particular task. Method : Using enumerate() + list comprehension This method can be
6 min read
MySQL-Connector-Python module in Python
MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting the data from the databases. SQL commands are case insensitive i.e CREATE and create signify the same command. In this article, we will be disc
2 min read
Python - Read blob object in python using wand library
BLOB stands for Binary Large OBject. A blob is a data type that can store binary data. This is different than most other data types used in databases, such as integers, floating point numbers, characters, and strings, which store letters and numbers. BLOB is a large complex collection of binary data which is stored in Database. Basically BLOB is us
2 min read
twitter-text-python (ttp) module - Python
twitter-text-python is a Tweet parser and formatter for Python. Amongst many things, the tasks that can be performed by this module are : reply : The username of the handle to which the tweet is being replied to. users : All the usernames mentioned in the tweet. tags : All the hashtags mentioned in the tweet. urls : All the URLs mentioned in the tw
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg