Python Exception Handling – Basic Examples

1. Basic try-except Block

python

# Basic exception handling
try:
num = int(input("Enter a number: "))
result = 10 / num
print(f"Result: {result}")
except:
print("Something went wrong!")

Example 1: Division with Zero Handling

python

# Handling division by zero error
try:
    num1 = int(input("Enter first number: "))
    num2 = int(input("Enter second number: "))
    result = num1 / num2
    print(f"Result: {result}")
except ZeroDivisionError:
    print("Error: Cannot divide by zero!")

Output:

text

Enter first number: 10
Enter second number: 0
Error: Cannot divide by zero!

Example 2: Invalid Input Handling

python

# Handling invalid input (non-integer values)
try:
    age = int(input("Enter your age: "))
    print(f"Your age is: {age}")
except ValueError:
    print("Error: Please enter a valid number!")

Output:

text

Enter your age: twenty
Error: Please enter a valid number!

Example 3: File Operations

python

# Handling file not found error
try:
    with open("non_existent_file.txt", "r") as file:
        content = file.read()
        print(content)
except FileNotFoundError:
    print("Error: File not found!")

Output:

text

Error: File not found!

Example 4: List Index Error

python

# Handling index out of range error
fruits = ["apple", "banana", "cherry"]

try:
    index = int(input("Enter index (0-2): "))
    print(f"Fruit at index {index}: {fruits[index]}")
except IndexError:
    print("Error: Index out of range!")
except ValueError:
    print("Error: Please enter a valid number!")

Output:

text

Enter index (0-2): 5
Error: Index out of range!

Example 5: Dictionary Key Error

python

# Handling key not found in dictionary
student = {"name": "John", "age": 20, "grade": "A"}

try:
    key = input("Enter key to search (name/age/grade): ")
    print(f"{key}: {student[key]}")
except KeyError:
    print(f"Error: Key '{key}' not found in dictionary!")

Output:

text

Enter key to search (name/age/grade): city
Error: Key 'city' not found in dictionary!

Bonus Example: Multiple Exception Handling

python

# Handling multiple types of exceptions
try:
    num = int(input("Enter a number: "))
    result = 100 / num
    print(f"100 divided by {num} is {result}")
    
except ValueError:
    print("Error: Please enter a valid integer!")
except ZeroDivisionError:
    print("Error: Cannot divide by zero!")
except Exception as e:
    print(f"Unexpected error: {e}")

Output:

text

Enter a number: abc
Error: Please enter a valid integer!

Key Points:

  1. try block: Contains code that might raise exceptions
  2. except block: Catches and handles specific exceptions
  3. Specific exceptions: Better than catching all exceptions
  4. User-friendly messages: Help users understand what went wrong
  5. Prevention: Better than handling errors after they occur

These examples show how to gracefully handle common errors that might crash your program!

1. Basic try-except Block

python

# Basic exception handling
try:
    num = int(input("Enter a number: "))
    result = 10 / num
    print(f"Result: {result}")
except:
    print("Something went wrong!")

2. Handling Specific Exceptions

python

try:
    num = int(input("Enter a number: "))
    result = 10 / num
    print(f"Result: {result}")
except ValueError:
    print("Please enter a valid number!")
except ZeroDivisionError:
    print("Cannot divide by zero!")

3. Handling Multiple Exceptions in One Block

python

try:
    num = int(input("Enter a number: "))
    result = 10 / num
    print(f"Result: {result}")
except (ValueError, ZeroDivisionError):
    print("Invalid input or division by zero!")

4. Using else Clause

python

try:
    num = int(input("Enter a number: "))
    result = 10 / num
except ValueError:
    print("Please enter a valid number!")
except ZeroDivisionError:
    print("Cannot divide by zero!")
else:
    print(f"Success! Result: {result}")  # Only runs if no exceptions

5. Using finally Clause

python

try:
    num = int(input("Enter a number: "))
    result = 10 / num
    print(f"Result: {result}")
except ValueError:
    print("Please enter a valid number!")
except ZeroDivisionError:
    print("Cannot divide by zero!")
finally:
    print("This always executes - cleanup code goes here")

6. Getting Exception Information

python

try:
    num = int(input("Enter a number: "))
    result = 10 / num
    print(f"Result: {result}")
except Exception as e:
    print(f"Error type: {type(e).__name__}")
    print(f"Error message: {e}")

7. File Handling Example

python

try:
    with open("myfile.txt", "r") as file:
        content = file.read()
        print(content)
except FileNotFoundError:
    print("File not found!")
except PermissionError:
    print("Permission denied!")
except IOError:
    print("Error reading file!")

8. List Index Handling

python

my_list = [1, 2, 3, 4, 5]

try:
    index = int(input("Enter index (0-4): "))
    print(f"Value at index {index}: {my_list[index]}")
except ValueError:
    print("Please enter a valid integer!")
except IndexError:
    print("Index out of range!")

9. Dictionary Key Handling

python

student = {"name": "John", "age": 20, "grade": "A"}

try:
    key = input("Enter key to search (name/age/grade/city): ")
    print(f"{key}: {student[key]}")
except KeyError:
    print(f"Key '{key}' not found in dictionary!")

10. Complete Example with All Clauses

python

def divide_numbers():
    try:
        num1 = int(input("Enter first number: "))
        num2 = int(input("Enter second number: "))
        result = num1 / num2
        
    except ValueError:
        print("Please enter valid integers!")
        return None
    except ZeroDivisionError:
        print("Cannot divide by zero!")
        return None
    except Exception as e:
        print(f"Unexpected error: {e}")
        return None
    else:
        print("Division successful!")
        return result
    finally:
        print("Calculation completed!")

# Run the function
result = divide_numbers()
if result is not None:
    print(f"Final result: {result}")

11. Nested Exception Handling

python

try:
    # Outer try block
    numbers = []
    
    try:
        # Inner try block
        num = int(input("How many numbers? "))
        for i in range(num):
            value = int(input(f"Enter number {i+1}: "))
            numbers.append(value)
            
    except ValueError:
        print("Invalid number entered!")
    
    # Continue with outer block
    if numbers:
        average = sum(numbers) / len(numbers)
        print(f"Average: {average}")
        
except ZeroDivisionError:
    print("No numbers were entered!")
except Exception as e:
    print(f"Unexpected error: {e}")

12. Simple Calculator with Error Handling

python

def calculator():
    try:
        num1 = float(input("Enter first number: "))
        operator = input("Enter operator (+, -, *, /): ")
        num2 = float(input("Enter second number: "))
        
        if operator == '+':
            result = num1 + num2
        elif operator == '-':
            result = num1 - num2
        elif operator == '*':
            result = num1 * num2
        elif operator == '/':
            result = num1 / num2
        else:
            print("Invalid operator!")
            return
            
        print(f"Result: {result}")
        
    except ValueError:
        print("Please enter valid numbers!")
    except ZeroDivisionError:
        print("Cannot divide by zero!")
    except Exception as e:
        print(f"An error occurred: {e}")

# Run calculator
calculator()

13. Input Validation with Retry

python

def get_valid_number():
    while True:
        try:
            num = int(input("Enter a positive number: "))
            if num <= 0:
                raise ValueError("Number must be positive!")
            return num
        except ValueError as e:
            print(f"Invalid input: {e}")
            print("Please try again!")

# Usage
number = get_valid_number()
print(f"You entered: {number}")

Key Points to Remember:

  1. try: Code that might raise exceptions
  2. except: Handles specific exceptions
  3. else: Runs if no exceptions occur
  4. finally: Always runs (good for cleanup)
  5. Use specific exceptions instead of general except:
  6. Always handle exceptions gracefully for better user experience

These examples cover the fundamental concepts of exception handling in Python!

Similar Posts

  • re.split()

    Python re.split() Method Explained The re.split() method splits a string by the occurrences of a pattern. It’s like the built-in str.split() but much more powerful because you can use regex patterns. Syntax python re.split(pattern, string, maxsplit=0, flags=0) Example 1: Splitting by Multiple Delimiters python import retext1=”The re.split() method splits a string by the occurrences of a pattern. It’s like…

  •  List Comprehensions 

    List Comprehensions in Python (Basic) with Examples List comprehensions provide a concise way to create lists in Python. They are more readable and often faster than using loops. Basic Syntax: python [expression for item in iterable if condition] Example 1: Simple List Comprehension Create a list of squares from 0 to 9. Using Loop: python…

  • binary files

    # Read the original image and write to a new file original_file = open(‘image.jpg’, ‘rb’) # ‘rb’ = read binary copy_file = open(‘image_copy.jpg’, ‘wb’) # ‘wb’ = write binary # Read and write in chunks to handle large files while True: chunk = original_file.read(4096) # Read 4KB at a time if not chunk: break copy_file.write(chunk)…

  • Nested for loops, break, continue, and pass in for loops

    break, continue, and pass in for loops with simple examples. These statements allow you to control the flow of execution within a loop. 1. break Statement The break statement is used to terminate the loop entirely. When break is encountered, the loop immediately stops, and execution continues with the statement immediately following the loop. Example:…

  • Special Sequences in Python

    Special Sequences in Python Regular Expressions – Detailed Explanation Special sequences are escape sequences that represent specific character types or positions in regex patterns. 1. \A – Start of String Anchor Description: Matches only at the absolute start of the string (unaffected by re.MULTILINE flag) Example 1: Match only at absolute beginning python import re text = “Start here\nStart…

  • Method Overloading

    Python does not support traditional method overloading in the way languages like C++ or Java do. If you define multiple methods with the same name, the last definition will simply overwrite all previous ones. However, you can achieve the same result—making a single method behave differently based on the number or type of arguments—using Python’s…

Leave a Reply

Your email address will not be published. Required fields are marked *