What Is try in Python? Absolute Beginners Tutorial

Final Exam & Certification

Complete this tutorial and pass the 10-question final exam to earn a downloadable certificate of completion.

skip to exam

Every program will eventually encounter bad input, missing files, or network failures. The try statement is how Python lets you handle those situations without the program crashing. This tutorial explains what try is, how it works, and how to combine it with except, else, and finally.

When Python runs a program and something goes wrong — dividing by zero, opening a file that does not exist, converting a string that is not a number — it raises an exception. Without any error handling, the program stops immediately and prints a traceback. The try statement gives you control over what happens instead.

What Is the try Statement?

The try statement marks a block of code that Python should attempt to run. If an error occurs anywhere inside that block, Python immediately stops executing it and looks for a matching except clause to handle the error. If no error occurs, the except block is skipped entirely.

Here is the simplest possible structure:

Key Concept

A try block does not prevent errors from happening. It gives you a place to respond to them gracefully instead of letting the program crash.

python
try:
    result = 10 / 0          # this line raises ZeroDivisionError
    print(result)
except ZeroDivisionError:
    print("You cannot divide by zero.")

When Python reaches 10 / 0 it raises a ZeroDivisionError. Because that line is inside a try block, Python does not crash. Instead it jumps straight to the except ZeroDivisionError: clause and prints the message.

Without the try statement the same code would produce this traceback and halt the program:

output
Traceback (most recent call last):
  File "example.py", line 1, in <module>
    result = 10 / 0
ZeroDivisionError: division by zero
Pro Tip

Always name the specific exception type in your except clause (e.g., except ValueError) rather than using a bare except:. Named exceptions catch only what you expect, so real bugs are still visible.

code builder click a token to place it

Build a valid try/except block that converts user input to an integer. Click the tokens in the correct order:

your code will appear here...
except ValueError: finally: n = int(input()) try: print("Not a number") except TypeError:
Why: The block must open with try:, followed by the indented code to attempt (n = int(input())). Then except ValueError: catches the specific error that int() raises when given a non-numeric string. finally: is for cleanup and does not catch errors. except TypeError: handles the wrong type of object entirely, not a bad string conversion.

except, else, and finally

A try block can be followed by up to three additional clauses. Each one serves a distinct purpose, and knowing when to use each one is the heart of writing clean error-handling code.

"Errors should never pass silently. Unless explicitly silenced." — Tim Peters, The Zen of Python (PEP 20)
When it runs
Only when an exception is raised in the try block and the exception type matches.
Common use
Respond to a specific error — display a message, use a default value, log the problem, or retry.
When it runs
Only when the try block completes successfully with no exception raised.
Common use
Code that depends on the try block succeeding, kept separate from the error-handling logic. For example, writing a result to a file after successfully reading data.
When it runs
Always — whether an exception occurred or not, whether it was caught or not.
Common use
Cleanup operations: closing file handles, releasing database connections, or freeing any resource that must be released regardless of what happened.

Here is a full example showing all four clauses together:

python
def parse_integer(text):
    """Convert a string to int, returning None if conversion fails."""
    try:
        value = int(text)
    except ValueError:
        print(f"Could not convert {text!r} to an integer.")
        return None
    else:
        print(f"Converted successfully: {value}")
        return value
    finally:
        print("parse_integer() finished.")

parse_integer("42")     # succeeds — else and finally both run
parse_integer("hello")  # fails  — except and finally both run
spot the bug click the line that contains the bug

The function below is supposed to safely convert a string to a float. It contains one bug. Click the line you think is wrong, then hit check.

1 def safe_float(text):
2 try:
3 return float(text)
4 except:
5 return None
The fix: Change except: to except ValueError:. A bare except: catches every exception including SystemExit and KeyboardInterrupt, which are not errors you want to silently swallow. Naming the exception type restricts the catch to the specific error float() raises on bad input, so unexpected problems still surface.

Catching Multiple Exception Types

A single try block can have as many except clauses as you need. Python checks them from top to bottom and runs the first one whose exception type matches the error that was raised. Only one except block runs per exception.

python
def safe_divide(a, b):
    """Divide a by b, returning None on error."""
    try:
        result = a / b
    except ZeroDivisionError:
        print("Cannot divide by zero.")
        return None
    except TypeError:
        print(f"Both arguments must be numbers, got {type(a).__name__} and {type(b).__name__}.")
        return None
    else:
        print(f"{a} / {b} = {result}")
        return result
    finally:
        print("safe_divide() finished.")

safe_divide(10, 2)      # no error          → else runs, then finally
safe_divide(10, 0)      # ZeroDivisionError → first except runs, then finally
safe_divide(10, "two")  # TypeError         → second except runs, then finally

You can also catch two exception types in a single except clause by grouping them in a tuple:

python
user_input = "abc"   # simulating bad user input
denominator = 0      # simulating a zero denominator

try:
    value = int(user_input) / denominator
except (ValueError, ZeroDivisionError) as err:
    print(f"Input error: {err}")
Watch Out

Place more specific exception types before more general ones. Exception is the base class for most built-in exceptions, so if you put it first it will match before your specific handlers ever get a chance to run.

Execution flow of a try/except/else/finally block — both the except and else paths converge at finally before the program continues.

How to Use try and except in Python

Follow these steps each time you write error-handling code. The pattern is the same whether you are reading files, parsing input, or calling an external API.

  1. Write the try block

    Start with the keyword try followed by a colon. On the next line, indent the code you want Python to attempt. Keep this block as small as possible — only include the lines that might raise an exception, not surrounding logic.

  2. Add a named except clause

    Directly below the try block, write except followed by the specific exception type you expect (e.g., except ValueError:) and a colon. Indent the error-handling code on the next line. Check the Python documentation or read the traceback from a test run to find the right exception name.

  3. Optionally add else for success code

    After your except clause, add an optional else block for code that should run only when no exception occurred. This keeps success logic clearly separate from error-handling logic and makes the code easier to read.

  4. Optionally add finally for cleanup

    Add a finally block after all except and else clauses. Code here runs no matter what happened — exception or not. Use it to close open files, release network connections, or reset any shared state.

Python Learning Summary Points

  1. The try statement wraps code that might raise an exception. If an error occurs inside it, Python jumps to the matching except clause rather than crashing the program.
  2. Always name the exception type in your except clause. A bare except: catches everything — including signals that are meant to stop your program — and hides real bugs.
  3. Use else for code that depends on the try block succeeding, and use finally for cleanup that must run regardless of what happened.

The try statement is one of the first tools that separates code that works in a test environment from code that holds up in the real world. Once you are comfortable with the basic structure, explore raise to intentionally throw exceptions and with statements, which handle many common cleanup scenarios automatically.

check your understanding question 1 of N

Frequently Asked Questions

The try statement tells Python to attempt running a block of code. If an error occurs inside the try block, Python stops executing that block and jumps to the matching except clause instead of crashing the entire program.

try defines the block of code to attempt. except defines what to do if a specific error occurs in that block. They always work together — you cannot write an except clause without a preceding try.

Yes. You can chain as many except clauses as you need after a single try block, each catching a different exception type. Python checks them in order from top to bottom and runs the first one that matches.

The optional else clause runs only when the try block completes without raising any exception. It is useful for code that should execute only on success, keeping it separate from the error-handling logic in except.

The finally clause always runs regardless of whether an exception occurred, was caught, or was not caught. It is typically used for cleanup actions such as closing files or releasing resources.

A try block must be followed by at least one except or finally clause. Using try with only finally (and no except) is valid when you want cleanup code but do not intend to suppress any exceptions.

If none of the except clauses match the exception type, the exception propagates up the call stack. If it is never caught anywhere, Python terminates the program and prints a traceback.

Using a bare except: clause (with no exception type specified) is generally discouraged because it catches every exception including SystemExit and KeyboardInterrupt, which can make programs difficult to stop and hide genuine bugs. Always specify the exception type you expect.

Certificate of Completion
Final Exam
Pass mark: 80% · Score 80% or higher to receive your certificate

Enter your name as you want it to appear on your certificate, then start the exam. Your name is used only to generate your certificate and is never transmitted or stored anywhere.

Question 1 of 10