Exception Handling in Python: Try and Except Statement

Exception Handling in Python: Try and Except Statement

12 Mar 2025
Intermediate
12.8K Views
25 min read
Learn with an interactive course and practical hands-on labs

Free DSA Online Course with Certification

Exception Handling in Python is an essential concept that helps you manage and control runtime errors, ensuring your program runs smoothly without unexpected crashes. Python provides the try, except, else, and finally blocks to handle exceptions effectively. Common exceptions include ZeroDivisionError, TypeError, ValueError, and FileNotFoundError.

In this Python tutorial, we explore how exception handling works in Python with examples. Whether you're a beginner or an experienced developer, this guide will help you write error-free and robust Python programs.

Exception handling is a technique in Python that deals with errors that occur during program execution.It entails spotting potential error situations, responding appropriately to exceptions when they arise, and identifying possible error conditions.Using the try and except keywords, Python provides a structured approach to exception handling.

By the end of this tutorial, you will gain a through understanding of:

  • The concept of exceptions and why they occur in Python
  • The difference between syntax errors and exceptions
  • How to use try, except, else, and finally blocks for handling exceptions
  • Catching specific exceptions vs. using a generic exception handler
  • Raising exceptions manually using the raise keyword
  • Using the assert statement for debugging and error handling

exception handling in python

Read More: Data Science with Python Certification Course

Different Types of Exceptions in Python:

Various built-in Python exceptions can be thrown when an error occurs during program execution. Here are some of the most popular types of Python exceptions:

  1. SyntaxError: When the interpreter comes across a syntactic problem in the code, such as a misspelled word, a missing colon, or an unbalanced pair of parentheses, this exception is raised.
  2. TypeError: When an operation or function is done to an object of the incorrect type, such as by adding a string to an integer, an exception is thrown.
  3. NameError: When a variable or function name cannot be found in the current scope, the exception NameError is thrown.
  4. IndexError: This exception is thrown when a list, tuple, or other sequence type's index is outside of bounds.
  5. KeyError: When a key cannot be found in a dictionary, this exception is thrown.
  6. ValueError: This exception is thrown when an invalid argument or input is passed to a function or method. An example would be trying to convert a string to an integer when the string does not represent a valid integer.
  7. AttributeError: When an attribute or method is not present on an object, such as when attempting to access a non-existent attribute of a class instance, the exception AttributeError is thrown.
  8. IOError: This exception is thrown if an input/output error occurs during an I/O operation, such as reading or writing to a file.
  9. ZeroDivisionError: This exception is thrown whenever a division by zero is attempted.
  10. ImportError: This exception is thrown whenever a module cannot be loaded or found by an import statement.
  11. FileNotFoundError:FileNotFoundError occurs when trying to open a file that does not exist.
  12. ModuleNotFoundError:ModuleNotFoundError occurs when trying to import a module that is not installed or does not exist.
  13. BaseException:The parent class for all built-in exceptions.
  14. Exception:The superclass for all non-exit exceptions.
Read More: Python Interview Questions and Answers

Understanding try, except, else, and finally Blocks in Python

1. try Block

  • This block contains the code that might cause an error.
  • If an error occurs, Python immediately jumps to the except block

2. except Block

  • This block catches and handles the error if one occurs in the try block.
  • We can specify different types of exceptions or use a general one.

3. else Block

  • Runs only if no exception occurs in the try block.
  • Useful when you want to execute some code only when there is no error.

4. finally Block

  • Runs no matter what happens, whether there is an exception or not.
  • Useful for cleanup tasks (e.g., closing a file or database connection).
Read More: Python Viva Interview Questions

Differences Between try and except in Python

FeatureErrorsExceptions
DefinitionSerious issues that stop the program from runningIssues that occur during execution but can be handled
CausesSyntax mistakes, missing modules, incorrect indentationIncorrect input, division by zero, file not found, etc.
HandlingCannot be handled using try-exceptCan be handled using try-except
ExamplesSyntaxError, IndentationError, MemoryErrorZeroDivisionError, FileNotFoundError, KeyError

Difference Between Exception and Error

FeatureExceptionError
DefinitionAn exception is an event that occurs during program execution and disrupts the normal flow of instructions.An error is a serious issue in the program that prevents it from continuing execution.
RecoverabilityCan be handled using try-except blocks.Generally, errors are unrecoverable and should be fixed in the code.
CausesCaused by logical mistakes, invalid user input, or unforeseen conditions.Caused by system failures, memory overflow, or hardware limitations.
ExamplesZeroDivisionError, IndexError, KeyError, FileNotFoundErrorMemoryError, StackOverflowError, OutOfMemoryError, SystemError
HandlingCan be caught and handled by the program.It cannot be caught easily and usually requires fixing the underlying issue.

Try and Except Statement – Catching Exceptions

  • In Python, you may catch and deal with exceptions by using the try and except commands.
  • The try and except clauses are used to contain statements that can raise exceptions and statements that handle such exceptions.
  • Exception handling in Python helps to manage errors in a program.
  • With exception handling in Python, you can prevent your code from crashing.

Example of Try and Except Statement in Python

        try:
  number = int(input("Enter a number: "))
  result = 10 / number
  print("The result is:", result)
except ZeroDivisionError:
  print("Division by zero is not allowed.")
except ValueError:
  print("Invalid input. Please enter a valid number.")

In this example in the Python Editor, the try block attempts to divide 10 by the input entered by the user. The result is calculated and reported if the input is a valid integer that is not zero. If the input is invalid (for example, a string) or zero, the corresponding except block raises an exception and displays an appropriate error message.

Output

Enter a number: 0
Division by zero is not allowed.

Catching Specific Exception

  • To provide handlers for various exceptions, a try statement may contain more than one except clause.
  • Please be aware that only one handler will be run at a time.
  • Exception handling in Python uses try and except blocks to catch errors.
  • Debugging becomes easier with exception handling in Python.

Example of Catching Specific Exception in Python

        try:
  file = open("test.txt", "r")
  contents = file.read()
  print(contents)
  file.close()
except FileNotFoundError:
  print("File not found.")
except IOError:
  print("An error occurred while reading the file.")

This code will attempt to open the file "test.txt" and read its contents. The code will print an error message if the file is not found. If an error occurs while reading the file, the code will display an error message before proceeding to the next line of code.

Output

File not found.
Read More: Python Developer Salary

Try with Else Clause

  • Python additionally allows the use of an else clause on a try-except block, which must come after every except clause.
  • Only when the try clause fails to throw an exception does the code go on to the else block.
  • Using exception handling in Python, you can write safer and more reliable programs.
Example of Try with Else Clause in Python
        try:
  # Open a file named "test.txt" for reading
  file = open("test.txt", "r")
  # Read the contents of the file
  contents = file.read()
  # Close the file
  file.close()
  # Check if the contents of the file contain the word "Python"
  if "Python" in contents:
    # If the word "Python" is found, print a message
    print("The word 'Python' is found in the file.")
  else:
    # If the word "Python" is not found, print a message
    print("The word 'Python' is not found in the file.")
except FileNotFoundError:
  # If the file "test.txt" is not found, print an error message
  print("The file 'test.txt' could not be found.")
else:
  # If no exceptions occur, print a message
  print("The file 'test.txt' was successfully read.")

A try block is used in this example to read "test.txt" and look for the word "Python." If the file access is successful, the otherwise block is executed. If an exception occurs, such as FileNotFoundError, the error is handled by the associated except block.

Output

The file 'test.txt' could not be found.

Finally Keyword in Python

  • The finalkeyword in Pythonis always used after the try and except blocks.
  • The try block normally terminates once the final block executes, or after the try block quits because of an exception.

Example of Finally Keyword in Python

        def divide_numbers(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        print("Error: Cannot divide by zero!")
    else:
        print(f"The result of {a} divided by {b} is: {result}")
    finally:
        print("This block always executes, regardless of exceptions.")
divide_numbers(10, 2)
divide_numbers(5, 0)

The code defines the function divide_numbers, which attempts to divide two numbers, prints the result if successful, handles the division by zero exception, and ensures that a final block of code (finally) always executes, regardless of whether an exception occurred or not.

Output

The result of 10 divided by 2 is: 5.0
This block always executes, regardless of exceptions.
Error: Cannot divide by zero!
This block always executes, regardless of exceptions.

Catch-All Handlers and Their Risks

  • Unintended Exception Handling:Catching all exceptions (except Exception:) may suppress critical errors, making debugging difficult.
  • Hidden Bugs:Swallowing exceptions without proper logging can obscure the root cause of issues.

Example of Catch-All Handlers and Their Risks in Python

        def risky_operation():
    raise ValueError("An unexpected error occurred.")

try:
    risky_operation()
except Exception as e:  # Catch-all handler
    print("An error occurred:", e)  # Risk: This might hide critical issues

Output

An error occurred: An unexpected error occurred.

Catching Multiple Exceptions

  • Handling Specific Errors: Catching multiple exceptions allows handling different error types separately.
  • Better Debugging:Helps identify the exact cause of failure rather than using a generic catch-all handler.

Example of Catching Multiple Exceptions in Python

def safe_divide(a, b):
    if b == 0:
        raise ZeroDivisionError("Cannot divide by zero.")
    return a / b
try:
    num1, num2 = map(int, input("Enter two numbers: ").split())
    result = safe_divide(num1, num2)
    print("The result is:", result)
except ZeroDivisionError as e:
    print("Error:", e)
except ValueError as e:
    print("Invalid input. Please enter numbers only.")

Output

Enter two numbers: 10 0
Error: Cannot divide by zero.

Raise an Exception

  • The raise statement enables the programmer to compel the occurrence of a particular exception.
  • Raise's lone argument specifies the exception that should be raised.
  • Either an exception instance or an exception class (a class deriving from Exception) must be present here.

Example of Raising Exception in Python

        def divide(a, b):
    if b == 0:
        raise ZeroDivisionError("Cannot divide by zero.")
    return a / b
try:
    result = divide(10, 2)
    print("The result is:", result)
except ZeroDivisionError as e:
    print("Error:", e)

The code in the Python Compiler implements a divide function to conduct division, throwing a ZeroDivisionError if the divisor is 0. It then attempts to call this method, prints the result if successful, and throws an exception if division by zero happens.

Output

The result is: 5.0

New Features in Exception Handling in Python 3.10 and 3.11

Python 3.10

  • Better Error Messages: Syntax errors now provide clearer and more specific messages, making debugging easier.
  • Pattern Matching for Exceptions: A new way to handle exceptions using structural pattern matching, making code more readable and organized.

Python 3.11

  • Faster Exception Handling:Performance improvements make exception handling up to 10-15% faster.
  • More Detailed Tracebacks:Tracebacks now highlight the exact line and expression where the error occurred, improving debugging.
  • Exception Groups:Allows multiple exceptions to be raised and handled together, useful for concurrent and batch processing.

Advantages of Exception Handling

  • Increased program dependability: By managing exceptions correctly, you can stop your program from crashing or generating wrong results because of unforeseen faults or input.
  • Error handling made easier: It is simpler to comprehend and maintain your code when you can separate the error management code from the core program logic using exception handling.
  • Simpler coding: With exception handling, you can write code that is clearer and easier to comprehend by avoiding the use of intricate conditional expressions to check for mistakes.
  • Simpler debugging: When an exception is raised, the Python interpreter generates a traceback that identifies the precise place in your code where the error happened.

Disadvantages of Exception Handling

  • Performance penalty: Because the interpreter must undertake an extra effort to detect and handle the exception, exception handling can be slower than utilizing conditional statements to check for mistakes.
  • Code complexity increase: Handling exceptions can make your code more difficult, especially if you have to deal with a variety of exception types or use sophisticated error-handling logic.
  • Possible security risks: It's critical to manage exceptions carefully and avoid disclosing too much information about your program because improperly handled exceptions may reveal sensitive information or lead to security flaws in your code.

Summary

Exception handling ensures that any mistake or unforeseen input does not cause the program to crash. Exception handling can be used to check both syntax levels and validations accordingly. Python Certification can help programmers learn these conventions and become more proficient in the language.

Python Exception Handling Quiz

Q 1: What is the purpose of the try-except block in Python?

  • To handle exceptions
  • To define functions
  • To iterate over lists
  • To declare variables

FAQs

The "ZeroDivisionError" that occurs when dividing by zero is an illustration of an exception in Python.

User-defined exceptions and built-in exceptions, such as ValueError and IndexError, are the two basic categories of exceptions in Python.

Python's "try" and "except" blocks are used to handle exceptions.

An exception explicitly relates to runtime defects that may be caught and handled in Python, whereas an error is a broader phrase that refers to mistakes in code.

Share Article
About Author
Sakshi Dhameja (Author and Mentor)

She is passionate about different technologies like JavaScript, React, HTML, CSS, Node.js etc. and likes to share knowledge with the developer community. She holds strong learning skills in keeping herself updated with the changing technologies in her area as well as other technologies like Core Java, Python and Cloud.

Accept cookies & close this