0
0
Pythonprogramming~5 mins

Try–except execution flow in Python

Choose your learning style9 modes available
Introduction

Try-except helps your program keep running even if something goes wrong. It catches errors and lets you handle them safely.

When you ask the user to enter a number but they might type letters instead.
When you open a file that might not exist.
When you divide numbers and want to avoid dividing by zero.
When you call a function that might fail sometimes.
When you want to give a friendly message instead of a crash.
Syntax
Python
try:
    # code that might cause an error
except SomeError:
    # code to handle the error
The try block runs code that might cause an error.
If an error happens, the except block runs to handle it.
Examples
This catches when the user types something that is not a number.
Python
try:
    x = int(input('Enter a number: '))
except ValueError:
    print('That is not a number!')
This catches the error when dividing by zero.
Python
try:
    result = 10 / 0
except ZeroDivisionError:
    print('Cannot divide by zero!')
This catches the error if the file does not exist.
Python
try:
    file = open('data.txt')
except FileNotFoundError:
    print('File not found!')
Sample Program

This program asks for a number. If the user types something wrong, it shows a friendly message instead of crashing.

Python
try:
    number = int(input('Enter a number: '))
    print(f'You entered {number}')
except ValueError:
    print('Oops! That was not a valid number.')
OutputSuccess
Important Notes

You can have multiple except blocks to handle different errors.

If no error happens, the except blocks are skipped.

Use except Exception as e: to catch any error and see what it is.

Summary

Try-except lets your program handle errors without stopping.

Put risky code inside try, and error handling inside except.

This makes your program friendlier and more reliable.