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

  • Static Methods

    The primary use of a static method in Python classes is to define a function that logically belongs to the class but doesn’t need access to the instance’s data (like self) or the class’s state (like cls). They are essentially regular functions that are grouped within a class namespace. Key Characteristics and Use Cases General…

  • Python Program to Check Pangram Phrases

    Python Program to Check Pangram Phrases What is a Pangram? A pangram is a sentence or phrase that contains every letter of the alphabet at least once. Method 1: Using Set Operations python def is_pangram_set(phrase): “”” Check if a phrase is a pangram using set operations “”” # Convert to lowercase and remove non-alphabetic characters…

  • Raw Strings in Python

    Raw Strings in Python’s re Module Raw strings (prefixed with r) are highly recommended when working with regular expressions because they treat backslashes (\) as literal characters, preventing Python from interpreting them as escape sequences. path = ‘C:\Users\Documents’ pattern = r’C:\Users\Documents’ .4.1.1. Escape sequences Unless an ‘r’ or ‘R’ prefix is present, escape sequences in string and bytes literals are interpreted according…

  • String Validation Methods

    Complete List of Python String Validation Methods Python provides several built-in string methods to check if a string meets certain criteria. These methods return True or False and are useful for input validation, data cleaning, and text processing. 1. Case Checking Methods Method Description Example isupper() Checks if all characters are uppercase “HELLO”.isupper() → True islower() Checks if all…

Leave a Reply

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