Exception Handling in Python

Module - 6 Functions in Python
Exception Handling in Python


Exceptions are mistakes discovered during execution. Exceptions are triggered whenever there is a mistake in a program. The program will come to a standstill if these exceptions are not handled. Python exception handling is essential to prevent the program from ending unexpectedly. This post will go over Exception Handling in Python in further detail.

What is Exception Handling in Python?

Exception handling in Python is a process of resolving errors that occur in a program. This involves catching exceptions, understanding what caused them, and then responding accordingly. Exceptions are errors that occur at runtime when the program is being executed. They are usually caused by invalid user input or code that is invalid in Python. Exception handling allows the program to continue to execute even if an error occurs.


   # code that may cause an exception
except ExceptionType as e:
   # code to handle the exception
   # code to execute if no exceptions were raised
   # code that will always be executed, regardless of exceptions

This is an example of the syntax for handling exceptions in Python. A try block contains code that can throw an exception ⚠️. If an exception occurs, the code in the except block is executed, which helps to handle the Exception. The else block is optional and is only executed if no exceptions occur. Finally, the code inside the finally block will always be executed regardless of any exceptions💯 .

Common Exceptions in Python

  1. NameError: This Exception is raised when a name is not found in the local or global namespace.
  2. IndexError: This Exception is raised when an invalid index is used to access a sequence.
  3. KeyError: This Exception is thrown when the key is not found in the dictionary.
  4. ValueError: This Exception is thrown when a built-in operation or function receives an argument of the correct type and incorrect value.
  5. IOError: This Exception is raised when an input/output operation fails, such as when an attempt is made to open a non-existent file.
  6. ImportError: This Exception is thrown when an import statement cannot find a module definition or a from ... import statement cannot find a name to import.
  7. SyntaxError: This Exception is raised when the input code does not conform to the Python syntax rules.
  8. TypeError: This Exception is thrown when an operation or function is applied to an object of inappropriate type
  9. AttributeError: occurs when an object does not have an attribute being referenced, such as calling a method that does not exist on an object.
  10. ArithmeticError: A built-in exception in Python is raised when an arithmetic operation fails. This Exception is a base class for other specific arithmetic exceptions, such as ZeroDivisionError and OverflowError.
  11. Floating point error: It is a type of arithmetic error that can occur in Python and other programming languages that use floating point arithmetic to represent real numbers.
  12. ZeroDivisionError: This occurs when dividing a number by zero, an invalid mathematics operation.
  13. FileExistsError: This is Python's built-in Exception thrown when creating a file or directory already in the file system.
  14. PermissionError: A built-in exception in Python is raised when an operation cannot be completed due to a lack of permission or access rights.

Try Except in Python

Python provides a way to catch specific exceptions during a program's execution. This is done with the "try" statement. The basic syntax looks like this:

   # code that may cause an exception
except ExceptionName:
   # code that will be executed if an exception occurs

For example, if we wanted to catch a ZeroDivisionError, we could do something like this:

x = 5 / 0
except ZeroDivisionError:
print("You can't divide by zero!")

This code will print "You can't divide by zero!" if a ZeroDivisionError is encountered during execution.

Raising Custom Exceptions in python

You can create custom exceptions in Python by creating a new exception class. To create a custom exception, you must define a new class inherited from the Exception class. You can add custom attributes, methods, and other logic to your custom exceptions as needed. Example:

class CustomError(Exception):
    """Custom Exception class"""
    def __init__(self, message):
        self.message = message
    raise CustomError("This is a custom exception")
except CustomError as e:

This code creates a custom exception class called CustomError. This exception class inherits from the base Exception class and has a custom message attribute. When the Exception is raised, the message is passed to the init  method and set as the message attribute. In the except block, the message attribute is printed.

Try except and ELSE!

Try and Except in Python is a way of handling errors and exceptions in Python. It is used to catch any errors that may occur during the execution of a program and provide a graceful way to handle them. The syntax for using try and except is as follows:

# code that may throw an exception
except ExceptionType:
# code to handle the exception
# code that will only execute if no exception was raised

The code inside the try block is executed until an exception is raised. If an exception is raised, the code inside the except block is executed. The code inside the else block is executed if no exception is raised.

Try Clause with Finally

  x = 5
  y = 0
  z = x/y
except ZeroDivisionError:
  print("Error: Cannot divide by zero")
  print("All done")

This code divides the variable x (set to 5) by the variable y (set to 0). Since this is impossible (dividing by 0), the code will throw a ZeroDivisionError. The except statement catches this error and prints a message to the user. The finally statement will run regardless of whether or not an error occurs, and in this case, it prints "All done".

Why Use Finally or Else in try..except?

Finally and Else are two keywords used in try..except blocks in Python. The Finally block executes a set of statements, regardless of the result of the try..except blocks. This is useful when you want to clean up resources like closing a file or connection, irrespective of whether an exception occurred or not. The Else block is used to execute a set of statements only if the try block does not raise an exception. It is useful for code that must be executed if the try block does not raise an exception.

What Happens if Errors are Raised in Except or Finally Block?

If an error is raised in an except or finally block, the error will be handled by the next outer try-except statement, or if there is no outer try-except statement, the error will be raised to the caller.

  x = 1/0
except ZeroDivisionError:
  print("Division by zero not allowed")
  except NameError:
    print("Variable y is not defined")

# Output: Variable y is not defined

This code is trying to divide 1 by 0, which will raise a ZeroDivisionError. This error is handled by the except block, which prints out "Division by zero not allowed". Then, the finally block tries to print the variable y, which is not defined. This raises a NameError, which is handled by the inner try-except statement in the finally block, which prints out "Variable y is not defined".


We learned about Exception Handling in Python, including how to raise and catch exceptions, use try-except blocks, create custom exceptions, and use the finally clause. We can now use our newfound knowledge to handle errors and exceptions in her Python code, enabling us to write more robust and reliable programs. 

Key takeaways

  1. Always use try-except blocks when catching exceptions
  2. Use finally to clean up resources that were used or allocated in the try block
  3. When handling exceptions, use specific exception handlers for specific exceptions
  4. Use raise to throw a custom exception 🚩
  5. Use logging to log exceptions for later debugging
  6. Use assertions to validate the correctness of code 🔍
  7. Always document the exceptions that a function or method can raise


  1. What is the correct syntax for raising an exception? 
    1. raise Exception 
    2. throw Exception  
    3. exit Exception 
    4. exit()

Answer: a. raise Exception

  1. What is the correct syntax to catch an exception in Python? 
    1. except Exception 
    2. catch Exception  
    3. try Exception 
    4. handle Exception

Answer:a. except Exception

  1. When will a finally block be executed in a try-except-finally statement?
    1. When an exception is caught  
    2. When an exception is not caught 
    3. After the try statement is executed 
    4. After the except statement is executed

Answer:c. After the try statement is executed

  1. What is the purpose of an else block in a try-except-else statement? 
    1. To execute code if an exception is not thrown  
    2. To execute code if an exception is thrown  
    3. To execute code regardless of whether an exception is thrown  
    4. To execute code after the try and except blocks are executed

Answer:a. To execute code if an exception is not thrown

Online Python Compiler
Open Compiler
Recommended Courses
Masters in CS: Data Science and Artificial Intelligence
20,000 people are doing this course
Join India's only Pay after placement Master's degree in Data Science. Get an assured job of 5 LPA and above. Accredited by ECTS and globally recognised in EU, US, Canada and 60+ countries.
Certification in Full Stack Data Science and AI
20,000 people are doing this course
Become a job-ready Data Science professional in 30 weeks. Join the largest tech community in India. Pay only after you get a job above 5 LPA.

AlmaBetter’s curriculum is the best curriculum available online. AlmaBetter’s program is engaging, comprehensive, and student-centered. If you are honestly interested in Data Science, you cannot ask for a better platform than AlmaBetter.

Kamya Malhotra
Statistical Analyst
Fast forward your career in tech with AlmaBetter

Vikash SrivastavaCo-founder & CPTO AlmaBetter

Vikas CTO

Related Tutorials to watch

Top Articles toRead

Made with heartin Bengaluru, India
  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • 4th floor, 315 Work Avenue, Siddhivinayak Tower, 152, 1st Cross Rd., 1st Block, Koramangala, Bengaluru, Karnataka, 560034
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

© 2023 AlmaBetter