Skip to content
Related Articles

Related Articles

Improve Article

Errors and Exceptions in Python

  • Difficulty Level : Hard
  • Last Updated : 17 Jun, 2020

Errors are the problems in a program due to which the program will stop the execution. On the other hand, exceptions are raised when the 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 syntax error is thrown.

Example




# 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 if statement a colon : is missing. We can fix this by writing the correct syntax.

logical errors(Exception)

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

Example 1:




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






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

Output:

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 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 run out of memory.
TypeErrorIt occurs when a function and operation is applied in an incorrect type.

Note: For more information, refer to Built-in Exceptions in Python

Error Handling

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

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

    Example




    # 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 limitation of certain condition then we can raise an exception.
    Example




    # 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
    

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :