---Advertisement---

Python Exception Handling: Complete Guide to try, catch, finally & raise with Best Examples 2025

By Bhavani

Updated On:

---Advertisement---
Python Exception Handling

๐Ÿ‘‰Python Exception Handling

Python Exception Handling: In Python, exceptions are errors that occur during program execution. Proper handling of these exceptions prevents program crashes and ensures smooth operation. This guide explains the key concepts of Python exception handling using try, catch, finally, and raise with examples.


๐Ÿ‘‰What is Exception Handling in Python?

Python Exception Handling: An exception is an error that occurs during program execution. Python automatically generates exceptions when errors are encountered, or you can manually trigger exceptions using the raise statement.

When exceptions are not properly handled, the program may terminate unexpectedly. To prevent this, Python provides structured exception handling.


๐Ÿ‘‰Common Examples of Exceptions in Python

  • Division by zero
  • Accessing a non-existent file
  • Adding incompatible data types
  • Accessing an invalid index in a list
  • Performing database operations on a disconnected server
  • Withdrawing more than the available balance in an ATM

๐Ÿ‘‰Why Use Exception Handling?

  • Ensures smooth program execution by managing errors effectively.
  • Helps isolate error-handling code from normal program logic.
  • Improves code readability and clarity.
  • Provides a structured way to handle errors in different program segments.
  • Allows the program to continue running even if errors occur.

๐Ÿ‘‰Python Exception Handling Keywords

Python Exception Handling: Python handles exceptions using these keywords:

  1. try
  2. catch (except in Python)
  3. finally
  4. raise

๐Ÿ‘‰1. Python try Statement

The try block contains the code that may raise an exception. If no exception occurs, the code inside the try block runs normally. If an exception occurs, control transfers to the corresponding except block.

๐Ÿ‘‰Syntax:

python

try:

    # Code that may raise an exception

    result = 10 / 0

except ZeroDivisionError:

    print(“Error: Division by zero is not allowed.”)


๐Ÿ‘‰2. Python except Statement (Equivalent to catch)

The except block is used to catch specific types of exceptions. Multiple except blocks can be used for different exception types.

๐Ÿ‘‰Example:

python

try:

    num = int(input(“Enter a number: “))

    print(10 / num)

except ZeroDivisionError:

    print(“Error: Cannot divide by zero.”)

except ValueError:

    print(“Error: Invalid input. Please enter a number.”)


๐Ÿ‘‰3. Python finally Statement

The finally block always executes, regardless of whether an exception occurred. It is often used for cleanup actions.

๐Ÿ‘‰Example:

python

try:

    file = open(“example.txt”, “r”)

    content = file.read()

    print(content)

finally:

    file.close()  # Ensures the file closes even if an error occurs

    print(“File closed successfully.”)


๐Ÿ‘‰4. Python raise Statement

The raise statement is used to trigger an exception manually. It is useful for custom error conditions.

๐Ÿ‘‰Syntax:

python

def check_age(age):

    if age < 18:

        raise ValueError(“Age must be 18 or above.”)

    print(“Access granted.”)

try:

    check_age(16)

except ValueError as e:

    print(f”Error: {e}”)


๐Ÿ‘‰Important Python Exceptions and Errors

Exception TypeDescription
ArithmeticErrorBase class for arithmetic errors like division by zero.
ImportErrorRaised when a module import fails.
IndexErrorRaised when accessing an invalid index in a list.
KeyErrorOccurs when a key is not found in a dictionary.
NameErrorRaised when referencing an undefined variable.
ValueErrorOccurs when a function receives an invalid argument.
EOFErrorRaised when input() reaches end-of-file condition.
ZeroDivisionErrorRaised when dividing by zero.
IOErrorOccurs during input/output operations.
SyntaxErrorRaised for syntax errors in code.
IndentationErrorRaised for incorrect indentation.

๐Ÿ‘‰Error vs. Exception

FeatureErrorException
DefinitionErrors are often serious issues that occur at runtime.Exceptions are manageable events that can be handled using try-except blocks.
RecoveryErrors are generally not recoverable.Exceptions can be handled and resolved.
ExamplesOutOfMemoryError, StackOverflowError.ValueError, IndexError, ZeroDivisionError.

๐Ÿ‘‰Summary

  • Python Exception Handling ensures smooth program execution by managing errors effectively.
  • Key keywords include try, except, finally, and raise.
  • Common exceptions like ZeroDivisionError, ValueError, and ImportError are handled efficiently using try-except blocks.
  • Using finally ensures code cleanup, while raise allows custom error triggering.

 Python File and Directory Renaming

Download Python

Leave a Comment

Index