#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
6 min read min read

Error Handling with Try-Except

Learn to handle errors gracefully and make robust programs

Error Handling with Try-Except

What are Errors?

When something goes wrong in your program, Python stops and shows an error message. This is called an exception.

Common situations that cause errors:

  • Opening a file that doesn't exist
  • Dividing by zero
  • Converting text to number when text isn't a number
  • Accessing list item that doesn't exist
  • Network connection fails

The problem: Errors crash your program. Users see confusing messages. Everything stops.

The solution: Error handling lets you catch errors and decide what to do instead of crashing.

Basic Try-Except Structure

code.py
try:
    # Code that might cause an error
except:
    # What to do if error happens

Simple example:

code.py
try:
    number = int("hello")
except:
    print("Cannot convert text to number")

What happens:

  • Python tries to convert "hello" to a number
  • This fails (you can't convert "hello")
  • Instead of crashing, it prints friendly message
  • Program continues running

Why This Matters

Without error handling:

code.py
age = int(input("Enter age: "))
print("Age in 10 years:", age + 10)

If user types "twenty": Program crashes with scary error message.

With error handling:

code.py
try:
    age = int(input("Enter age: "))
    print("Age in 10 years:", age + 10)
except:
    print("Please enter a number")

If user types "twenty": Shows friendly message. Program doesn't crash.

Catching Specific Errors

It's better to catch specific error types instead of all errors.

Common Error Types

  1. ValueError - Wrong value type
code.py
try:
    number = int("hello")
except ValueError:
    print("That's not a valid number")
  1. ZeroDivisionError - Dividing by zero
code.py
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")
  1. FileNotFoundError - File doesn't exist
code.py
try:
    file = open("missing.txt", "r")
except FileNotFoundError:
    print("File not found")
  1. IndexError - List index out of range
code.py
try:
    numbers = [1, 2, 3]
    print(numbers[10])
except IndexError:
    print("Index doesn't exist")
  1. KeyError - Dictionary key doesn't exist
code.py
try:
    data = {"name": "John"}
    print(data["age"])
except KeyError:
    print("Key not found")

Multiple Except Blocks

Handle different errors differently.

code.py
try:
    number = int(input("Enter number: "))
    result = 100 / number
    print("Result:", result)
except ValueError:
    print("Please enter a valid number")
except ZeroDivisionError:
    print("Number cannot be zero")

What this does:

  • If user enters text: shows "Please enter a valid number"
  • If user enters 0: shows "Number cannot be zero"
  • If user enters valid number: shows result

Catching Multiple Errors in One Block

code.py
try:
    number = int(input("Enter number: "))
    result = 100 / number
except (ValueError, ZeroDivisionError):
    print("Invalid input or zero")

What this does: Handles both ValueError and ZeroDivisionError with same message.

The Else Clause

Code in else runs only if no errors occurred.

code.py
try:
    number = int(input("Enter number: "))
except ValueError:
    print("Invalid number")
else:
    print("You entered:", number)
    print("Double:", number * 2)

What this does:

  • If error: shows "Invalid number"
  • If no error: shows the number and its double

When to use else: When you have code that should only run if everything worked.

The Finally Clause

Code in finally always runs, whether error happened or not.

code.py
try:
    file = open("data.txt", "r")
    content = file.read()
except FileNotFoundError:
    print("File not found")
finally:
    print("Cleanup complete")

What this does: "Cleanup complete" prints whether file was found or not.

Common use: Closing files, cleaning up resources, logging.

code.py
file = None
try:
    file = open("data.txt", "r")
    content = file.read()
    print(content)
except FileNotFoundError:
    print("File not found")
finally:
    if file:
        file.close()
        print("File closed")

Getting Error Details

You can get information about the error.

code.py
try:
    number = int("hello")
except ValueError as error:
    print("Error occurred:", error)

What this shows: "Error occurred: invalid literal for int() with base 10: 'hello'"

Another example:

code.py
try:
    result = 10 / 0
except ZeroDivisionError as e:
    print("Error type:", type(e))
    print("Error message:", e)

Raising Errors

You can create your own errors when something is wrong.

code.py
def set_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative")
    print("Age set to:", age)

try:
    set_age(-5)
except ValueError as e:
    print("Error:", e)

What this does: If age is negative, raises ValueError with custom message.

When to raise errors: When your function receives invalid input or encounters impossible situations.

Practice Example

The scenario: You're building a calculator that handles user input safely.

code.py
def safe_divide():
    try:
        num1 = input("Enter first number: ")
        num2 = input("Enter second number: ")

        n1 = float(num1)
        n2 = float(num2)

        result = n1 / n2

        print("Result:", result)
        return result

    except ValueError:
        print("Error: Please enter valid numbers")
        return None

    except ZeroDivisionError:
        print("Error: Cannot divide by zero")
        return None

    except Exception as e:
        print("Unexpected error:", e)
        return None

    finally:
        print("Calculation attempt finished")

result = safe_divide()

if result is not None:
    print("Operation successful")
    print("Rounded:", round(result, 2))
else:
    print("Operation failed")

What this program does:

  1. Gets two numbers from user
  2. Tries to convert them to floats
  3. Tries to divide them
  4. Handles text input error
  5. Handles division by zero error
  6. Handles any unexpected errors
  7. Always shows "attempt finished"
  8. Returns result or None
  9. Checks if operation succeeded

Nested Try-Except

You can have try-except inside try-except for complex error handling.

code.py
try:
    file_name = input("Enter file name: ")
    with open(file_name, "r") as file:
        try:
            number = int(file.read())
            print("Number is:", number)
        except ValueError:
            print("File doesn't contain a valid number")
except FileNotFoundError:
    print("File not found")

What this does:

  • Outer try-except handles file not found
  • Inner try-except handles invalid number in file

Key Points to Remember

Use try-except to handle errors gracefully instead of letting programs crash. Put risky code in try block, error handling in except.

Catch specific error types (ValueError, FileNotFoundError, etc.) instead of catching all errors. This makes debugging easier.

else clause runs only if no errors occurred. finally clause always runs, whether error happened or not.

You can get error details using "except ErrorType as variable". Use raise to create your own errors.

Error handling makes programs robust and user-friendly. Always handle errors where user input or external resources are involved.

Common Mistakes

Mistake 1: Catching all errors blindly

code.py
try:
    code_here()
except:  # Too broad!
    pass  # Hides all errors, even bugs

Better:

code.py
try:
    code_here()
except ValueError:  # Specific error
    print("Invalid value")

Mistake 2: Empty except block

code.py
try:
    number = int(input("Number: "))
except ValueError:
    pass  # User doesn't know what went wrong

Always give feedback.

Mistake 3: Try block too large

code.py
try:
    # 50 lines of code
except ValueError:
    print("Error")

Only wrap risky code in try block.

Mistake 4: Using finally for normal code

code.py
try:
    x = 5 + 5
finally:
    print(x)  # This is not cleanup!

finally is for cleanup (closing files, connections), not normal logic.

What's Next?

You now know how to handle errors and make robust programs. You've completed Module 2! You've learned about lists, tuples, dictionaries, sets, comprehensions, file operations, and error handling. These are the building blocks for working with data in Python.