Python Try....Except


Errors are common when you write programs, especially when dealing with user input, files, APIs or calculations. Python gives you a clean way to handle errors using the try and except blocks. Instead of your program crashing, you can catch the error, show a friendly message and continue running safely.

In this tutorial, you will learn how try and except work, how to handle multiple errors, how to use the else and finally blocks and how to raise your own errors. You will also see real-life examples and simple explanations that help you understand why exception handling is important in Python.

What Is Exception Handling?

Exception handling means catching errors in your program so that the program doesn’t stop suddenly. Instead of showing long error messages, you can handle the issue smoothly.

For example:

  • Wrong user input

  • Dividing by zero

  • File not found

  • Invalid data type

  • Network timeout

Python allows you to manage such situations using try and except.

The try and except Structure

The basic structure looks like this:

try:
    # Code that may cause an error
except:
    # Code that runs if there is an error

When the code inside try runs successfully, Python skips except. If an error occurs, Python jumps directly to except.

Simple Example

try:
    x = 10 / 0
except:
    print("Something went wrong.")

Output:

Something went wrong.

Instead of crashing the program, Python catches the error and prints the message.

Catching Specific Exceptions

Catching all errors is possible, but not recommended. It’s better to catch specific exceptions so you know exactly what went wrong.

Example:

try:
    number = int("hello")
except ValueError:
    print("Please enter numbers only.")

Here, only ValueError is handled.

Common exceptions include:

  • ValueError

  • TypeError

  • ZeroDivisionError

  • FileNotFoundError

  • IndexError

  • KeyError

Handling Multiple Exceptions

You can handle different errors using multiple except blocks.

Example:

try:
    value = 10 / int(input("Enter a number: "))
except ZeroDivisionError:
    print("You cannot divide by zero.")
except ValueError:
    print("Please enter a valid number.")

Each except block handles a different problem.

Using One Block for Multiple Errors

Sometimes you want to handle several errors the same way. You can combine them in a tuple.

try:
    number = int(input("Enter: "))
    result = 10 / number
except (ValueError, ZeroDivisionError):
    print("Invalid input.")

Using else With try

The else block runs only when the try block runs without errors.

Example:

try:
    x = 10 / 2
except ZeroDivisionError:
    print("Error occurred.")
else:
    print("No error. Result is:", x)

Using finally

finally always runs whether an error occurs or not. It is used for cleanup tasks like closing files or database connections.

Example:

try:
    file = open("sample.txt")
    data = file.read()
except FileNotFoundError:
    print("File not found.")
finally:
    print("Closing the program.")

Output:

File not found.
Closing the program.

Raising Your Own Errors

Sometimes you want to create an error manually for validation.

Example:

age = -5

if age < 0:
    raise ValueError("Age cannot be negative.")

This stops execution and shows your custom message.

Working With try inside functions

You can catch errors inside functions to avoid breaking larger programs.

def divide(a, b):
    try:
        return a / b
    except ZeroDivisionError:
        return "Cannot divide by zero."

Calling:

print(divide(10, 0))

Real-Life Example: User Input

try:
    marks = int(input("Enter marks: "))
except ValueError:
    print("Please type numbers only.")

This avoids input errors in user-based programs.

Real-Life Example: Reading Files

try:
    f = open("data.txt")
    print(f.read())
except FileNotFoundError:
    print("The file does not exist.")

This is useful when working with external resources.

Real-Life Example: Dictionary Keys

student = {"name": "Aarohi"}

try:
    print(student["age"])
except KeyError:
    print("Age not found.")

Combining try and finally

Useful for closing files:

try:
    f = open("demo.txt", "w")
    f.write("Hello")
finally:
    f.close()

Even if there is an error, the file closes properly.

Practical Examples

  1. Convert user input safely

try:
    value = int(input("Enter number: "))
except ValueError:
    print("Enter valid number.")
  1. Handle division errors

try:
    print(10 / 0)
except ZeroDivisionError:
    print("Cannot divide by zero.")
  1. Check list index

try:
    nums = [1, 2, 3]
    print(nums[5])
except IndexError:
    print("Index out of range.")
  1. Handle missing files

try:
    open("hello.txt")
except FileNotFoundError:
    print("File missing.")
  1. Handle type mistakes

try:
    print("age" + 20)
except TypeError:
    print("Wrong type.")
  1. Multiple except blocks

try:
    x = int("hi")
except ValueError:
    print("Invalid number.")
  1. Use else

try:
    x = 5 * 10
except:
    print("Error")
else:
    print("Success:", x)
  1. Use finally

try:
    print("Start")
finally:
    print("Done")
  1. Raise custom error

raise ValueError("Invalid data")
  1. Function with error handling

def safe_div(a, b):
    try:
        return a / b
    except ZeroDivisionError:
        return "Error"

Summary of the Tutorial

try and except blocks help you handle errors safely without stopping the program. You learned how to catch specific exceptions, use multiple except blocks, use else and finally, raise custom errors and build safe programs with real examples. Exception handling makes your code more reliable and helps prevent crashes in real applications.


Practice Questions

Q1. Write a Python program to catch a ZeroDivisionError and print a friendly message.

Q2. Write a Python program to use try...except to handle input that can’t be converted to an integer.

Q3. Write a Python program to open a missing file and handle the FileNotFoundError.

Q4. Write a Python program to create a function that raises a ValueError when the input is negative.

Q5. Write a Python program to use try...except...else to show a message when no error occurs.

Q6. Write a Python program to print "Always runs" using a finally block.

Q7. Write a Python program to catch both IndexError and KeyError in separate except blocks.

Q8. Write a Python program to use raise to stop execution if a variable is empty.

Q9. Write a Python program to nest try-except blocks and handle errors at both levels.

Q10. Write a Python program to use a try block to take input and a finally block to always close the process or display a message.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top