StudyLover
  • Home
  • Study Zone
  • Profiles
  • Typing Tutor
  • Contact us
  • Sign in
StudyLover Exception Handling
Download
  1. Python
  2. Pyhton MCA (Machine Learning using Python)
  3. Unit 3: Getting Started with Python: A Guide to Syntax, Data Structures, and OOP
Looping : User-defined functions
Unit 3: Getting Started with Python: A Guide to Syntax, Data Structures, and OOP

Exception Handling is a critical concept in programming that allows you to manage errors gracefully. When an error occurs during the execution of a program, Python creates an exception object. If this exception is not "handled," the program will crash and display a traceback message. Exception handling provides a structured way to "catch" these errors and execute specific code to deal with them, preventing the program from crashing and allowing it to continue running or terminate cleanly.

1. The try...except Block

This is the fundamental structure for handling exceptions. The code that might cause an error is placed inside the try block. If an error occurs, the code inside the corresponding except block is executed.

  • Use Case: To prevent a program from crashing due to a predictable error, such as a user entering invalid input or attempting to divide by zero.

Python

# --- try...except Example ---

try:

    # This code might cause an error

    numerator = 10

    denominator = int(input("Enter a number to divide by: "))

    result = numerator / denominator

    print(f"The result is: {result}")

# This block runs ONLY if a ZeroDivisionError occurs

except ZeroDivisionError:

    print("Error: You cannot divide by zero!")

# This block runs ONLY if a ValueError occurs (e.g., user enters text)

except ValueError:

    print("Error: You must enter a valid number!")

 

print("Program execution continues...")


2. Catching Specific vs. General Exceptions

It's best practice to catch specific exceptions (like ValueError or ZeroDivisionError) whenever possible. This allows you to handle different errors in different ways. You can catch a general Exception, but this can sometimes hide bugs because it will catch all types of errors.

  • Use Case: Providing specific feedback to the user based on the exact type of error that occurred.

Python

# --- Catching Multiple Specific Exceptions ---

my_list = [1, 2, 3]

try:

    index = int(input("Enter an index to access: "))

    value = my_list[index]

    print(f"The value at index {index} is {value}.")

except ValueError:

    print("Error: Please enter a valid integer for the index.")

except IndexError:

    print(f"Error: Index {index} is out of range for the list.")

except Exception as e: # A general catch-all for any other unexpected error

    print(f"An unexpected error occurred: {e}")


3. The else Block

The else block is optional and is executed only if the try block completes without raising any exceptions.

  • Use Case: To run code that should only execute if the potentially problematic code in the try block was successful. This helps to separate the "success" logic from the main try block.

Python

# --- else Block Example ---

try:

    number = int(input("Enter a positive number: "))

    if number <= 0:

        # We can manually raise an error to be caught by the except block

        raise ValueError("That is not a positive number!")

except ValueError as e:

    print(f"Error: {e}")

else:

    # This code runs ONLY if the try block succeeds without any errors

    print("Thank you! You entered a valid positive number.")


4. The finally Block

The finally block is optional and is always executed, regardless of whether an exception occurred or not.

  • Use Case: For cleanup actions that must happen no matter what. The most common example is closing a file or a network connection to ensure that resources are released properly, even if an error occurred while processing them.

Python

# --- finally Block Example ---

file = None # Initialize file to None

try:

    print("Opening file...")

    file = open("my_file.txt", "w")

    # The next line will cause an error because we are trying to write an integer

    file.write(123)

    print("Writing to file...")

except TypeError:

    print("Error: Can only write strings to a text file.")

finally:

    # This block will run whether an error occurred or not

    print("Executing finally block...")

    if file:

        file.close()

        print("File closed.")


5. Raising Exceptions (raise)

You can manually trigger an exception at any point in your code using the raise keyword.

  • Use Case: To enforce rules or validate input in your own functions. If a function receives an invalid argument, it can raise an appropriate error to signal that something is wrong.

Python

# --- raise Example ---

def set_age(age):

    if not isinstance(age, int):

        raise TypeError("Age must be an integer.")

    if age < 0:

        raise ValueError("Age cannot be negative.")

    print(f"Age set to {age}.")

 

try:

    set_age(25)

    set_age(-5) # This will raise a ValueError

except ValueError as e:

    print(f"Caught an error: {e}")

 

# Output:

# Age set to 25.

# Caught an error: Age cannot be negative.

 

Looping User-defined functions
Our Products & Services
  • Home
Connect with us
  • Contact us
  • +91 82955 87844
  • Rk6yadav@gmail.com

StudyLover - About us

The Best knowledge for Best people.

Copyright © StudyLover
Powered by Odoo - Create a free website