python-backend
/

Python Error Handling – Robust Code with Exceptions

Last Sync: Today

On this page

5
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

python-backend

Python Error Handling – Robust Code with Exceptions

Understanding Exceptions

In Python, errors detected during execution are called Exceptions. If an exception is not handled, the program terminates abruptly. Handling these gracefully ensures your application can recover from unexpected situations like missing files, network failures, or invalid user input.

The Try...Except Block

The try block contains the code that might raise an error, while the except block contains the code that handles the error. You should always aim to catch specific exceptions rather than using a blanket except: statement.

PythonRead-only
1
try:
    number = int(input("Enter a number: "))
    result = 10 / number
except ValueError:
    print("Invalid input! Please enter a numeric value.")
except ZeroDivisionError:
    print("Cannot divide by zero!")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

Else and Finally

Python provides two additional keywords to make error handling more precise:

  • else: Runs only if the code in the try block did NOT throw an exception.
  • finally: Always runs, regardless of whether an exception occurred or not. This is typically used for cleanup actions (e.g., closing a database connection).

Raising Exceptions

You can manually trigger an exception using the raise keyword. This is useful for enforcing business logic or validation rules.

PythonRead-only
1
def set_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative!")
    return f"Age set to {age}"

# Usage
try:
    set_age(-5)
except ValueError as e:
    print(e) # Output: Age cannot be negative!

Comparison: Error Handling Patterns

KeywordPurposeRequirement
tryTest a block of code for errorsMandatory
exceptHandle the errorAt least one (or finally)
elseRun code if no error occurredOptional
finallyAlways execute (cleanup)Optional
raiseManually trigger an errorOptional

Try it yourself

def divide_numbers(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        return "Error: You cannot divide by zero."
    except TypeError:
        return "Error: Both inputs must be numbers."
    else:
        return f"The result is {result}"
    finally:
        print("Execution of divide_numbers finished.")

# Try changing these values!
print(divide_numbers(10, 2))
print(divide_numbers(10, 0))
print(divide_numbers(10, '5'))

Test Your Knowledge

Q1
of 3

Which block is used to run code ONLY if no exceptions were raised?

A
finally
B
except
C
else
D
catch
Q2
of 3

Which keyword is used to manually trigger an exception in Python?

A
throw
B
raise
C
trigger
D
error
Q3
of 3

In a try...except...finally sequence, which block is guaranteed to run?

A
try
B
except
C
finally
D
else

Frequently Asked Questions

What is the difference between a Syntax Error and an Exception?

A Syntax Error occurs when the parser detects incorrect code structure (e.g., missing colon). An Exception occurs during runtime even if the syntax is correct (e.g., ZeroDivisionError).

Can I catch multiple exceptions in one block?

Yes, you can use a tuple: except (ValueError, TypeError): to handle multiple different error types with the same logic.

What is the 'with' statement?

The with statement simplifies exception handling by encapsulating common preparation and cleanup tasks (Context Managers). It is most commonly used for opening files safely.

Previous

python modules

Next

python virtualenv

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.