← Back to Chapters

Python Try Except

? Python Try Except

⚡ Quick Overview

In Python, runtime errors (exceptions) can stop your program from executing. To prevent sudden crashes and handle problems gracefully, you use try, except, else, and finally blocks.

The idea: put “risky” code inside try. If an error occurs, the corresponding except block runs instead of the program crashing.

? Key Concepts

  • try – contains the code that might raise an exception.
  • except – handles the error if one occurs.
  • Specific exceptions – like ValueError, ZeroDivisionError, etc.
  • else – runs only if no exception was raised in the try block.
  • finally – always runs, whether an error occurred or not (often used for cleanup).
  • Multiple except blocks – to handle different exception types differently.

? Syntax and Flow

General structure of exception handling in Python:

try:
    # code that may raise an exception
except SomeExceptionType:
    # handle specific exception
except AnotherExceptionType:
    # handle another exception
else:
    # runs if no exception was raised
finally:
    # runs no matter what (cleanup code)

The else and finally blocks are optional, but they help separate “normal success code” (else) from “always-run cleanup code” (finally).

? Code Examples

? Basic try-except

This example catches any exception and prints a friendly message instead of crashing.

? View Code Example
try:
    # risky operation: may raise ZeroDivisionError
    x = 10 / 0
except:
    # generic error handler
    print("Something went wrong!")

? Catching a specific exception

It is better to catch specific exception types like ValueError so that unexpected errors don’t get silently swallowed.

? View Code Example
try:
    # convert string to integer (this will fail)
    num = int("hello")
except ValueError:
    # handle invalid integer conversion
    print("Invalid number!")

? Using else with try-except

The else block runs only when the try block does not raise any exception.

? View Code Example
try:
    # code that may raise an exception
    print("No error here")
except:
    # runs if an exception is raised
    print("Error occurred")
else:
    # runs only if no exception was raised
    print("Everything worked fine!")

? Using finally for cleanup

The finally block is mainly used for cleanup actions such as closing files or network connections.

? View Code Example
try:
    # attempt to open and read a file
    f = open("file.txt")
    f.read()
except FileNotFoundError:
    # handle missing file error
    print("File not found")
finally:
    # cleanup or final message that always runs
    print("This will always run")

⚠️ Multiple except blocks

You can handle different types of errors separately using multiple except blocks.

? View Code Example
try:
    # this line may raise ValueError or ZeroDivisionError
    x = int("text") / 0
except ValueError:
    # handle invalid integer conversion
    print("Value error occurred")
except ZeroDivisionError:
    # handle division by zero
    print("Cannot divide by zero")

? Live Output and Explanation

? Basic try-except output

Code: dividing by zero inside the try block.

Without exception handling, Python would raise ZeroDivisionError and stop the program.

With the try-except block, the output is:

Something went wrong!

? ValueError example output

When Python tries to run int("hello"), it fails because the string "hello" cannot be converted to an integer. This raises a ValueError.

The except ValueError block catches it and prints:

Invalid number!

? Else and finally behavior

  • If no error occurs in the try block, the else block runs.
  • The finally block always runs, whether an exception happened or not.

This separation helps you clearly express: “what happens on success”, “what happens on error”, and “what must happen in all cases”.

? Tips and Best Practices

  • Prefer catching specific exceptions (e.g., ValueError, ZeroDivisionError) instead of a bare except:.
  • Use finally for cleanup tasks such as closing files, network connections, or database cursors.
  • Keep your try blocks small and focused so that you don’t accidentally hide unrelated bugs.
  • Log or print useful messages inside except blocks to make debugging easier.
  • Use else for code that should only run when everything in try succeeds.

? Try It Yourself

  • Write a program that asks the user for a number using input(). Handle non-numeric input using try-except and show a friendly error message.
  • Try to open a non-existent file and catch the FileNotFoundError. Print a message like "File does not exist".
  • Create a small program that uses try-except-else-finally:
    • try – read a number and divide 100 by it.
    • except – handle invalid input or division by zero.
    • else – print the result if everything went well.
    • finally – print a message like "Program ended".