Open In App

Errors and Exceptions in Python

Last Updated : 22 Oct, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Errors are the problems in a program due to which the program will stop the execution. On the other hand, exceptions are raised when some internal events occur which changes the normal flow of the program. 
Two types of Error occurs in python. 
 

  1. Syntax errors
  2. Logical errors (Exceptions) 
     

 

Syntax errors

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

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:
 

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

logical errors(Exception)

When in the runtime an error that occurs after passing the syntax test is called exception or logical type. For example, when we divide any number by zero then the ZeroDivisionError exception is raised, or when we import a module that does not exist then ImportError is raised.
Example 1: 
 

Python3




# initialize the amount variable
marks = 10000
  
# perform division with 0
a = marks / 0
print(a)


Output:
 

In the above example the ZeroDivisionError as we are trying to divide a number by 0.
Example 2: When indentation is not correct. 
 

Python3




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


Output:
 

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

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.
    Example 
     

Python3




# 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. 
    Example 
     

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


Previous Article
Next Article

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 Catch Multiple Exceptions in One Line in Python?
Prerequisites: Exception handling 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 t
1 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
Handle Unhashable Type List Exceptions in Python
Python, with its versatile and dynamic nature, empowers developers to create expressive and efficient code. However, in the course of Python programming, encountering errors is inevitable. One such common challenge is the "Unhashable Type List Exception". In this article, we will dive deep into the intricacies of Unhashable Type List Exception in P
3 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
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
Article Tags :
Practice Tags :