Python try...except Statements: Handling Exceptions
Learn how Python try...except handles runtime exceptions, validates integer input, avoids unwanted tracebacks, and separates success and failure paths with else.
What Are Errors and Exceptions?
Programs can fail in different ways. An exception is a runtime event, usually an error condition, that disrupts the normal sequence of execution. Exception handling is code that detects and responds to exceptions in a controlled way.
A runtime error is discovered while a program is running. For example, int() cannot convert every string into an integer. If a user enters blue when a number is expected, the conversion raises a ValueError.
Exceptions are different from other common error categories:
When an exception is not handled, Python displays a traceback. A traceback is diagnostic output showing where the exception occurred. The affected program flow stops at that point.
For a broader comparison of error categories, see Python error types and syntax and logical errors.
The Purpose of try...except
A try statement lets you protect an operation that might raise an exception.
- The try block is the indented code suite containing the operation that may fail.
- The except clause is the handler that runs when an exception from its associated
tryblock is caught.
The handler can display a useful message, choose an alternative action, or recover from an expected problem. This allows a program to respond to expected invalid situations more gracefully instead of terminating immediately.
Basic try...except Syntax
try:
# Code that might raise an exception
risky_operation()
except:
# Fallback or recovery behavior
print("Something went wrong")
The except clause must follow its associated try block. The two clauses align at the same indentation level, and each clause has an indented suite beneath it. Python uses indentation to identify the code belonging to each block.
A typical specific handler names the exception that you expect:
try:
number = int("not a number")
except ValueError:
print("That value is not a valid integer.")
Use a specific exception type when you know which expected problem you want to handle. ValueError is a common exception raised when a function receives a value of the right general type but unacceptable content or format, such as invalid text passed to int().
How Execution Flows
Python executes statements in the try suite in order.
- If no exception occurs, all statements in the
trysuite finish, and theexceptsuite is skipped. - If an exception occurs, execution stops at the failing statement in the
trysuite. - Statements after the failing statement in that
trysuite do not run for that attempt. - Python searches for a matching handler. If it finds one, the corresponding
exceptsuite runs.
try:
print("First")
value = int("green")
print("Third")
except ValueError:
print("The conversion failed")
print("After the try statement")
This prints First, then The conversion failed, then After the try statement. It does not print Third, because the conversion fails before that statement.
Handling Invalid User Input
input() always returns text. To use that response as an integer, pass it to int(). Numeric text such as "16" can be converted, but alphabetic text such as "sixteen" raises ValueError.
Age Prompt Without Exception Handling
age_text = input("How old are you? ")
age = int(age_text)
if age >= 18:
print("You meet the age requirement.")
else:
print("You do not meet the age requirement.")
With valid input such as 21, the conversion succeeds and the conditional decision runs. With input such as twenty-one, int(age_text) raises ValueError. The program stops at that statement and displays a traceback.
Protecting the Conversion
age_text = input("How old are you? ")
try:
age = int(age_text)
except ValueError:
print("Please enter your age as a whole number.")
else:
if age >= 18:
print("You meet the age requirement.")
else:
print("You do not meet the age requirement.")
For input 21, conversion succeeds, the except suite is skipped, and the age decision runs. For input twenty-one, the handler displays a user-facing invalid-input message, and the age decision is not attempted.
The conversion is placed in the try block because it is the operation expected to raise ValueError. The comparison is placed in else because it depends on successful conversion.
You can learn more about receiving user input in Python input() and about numeric values in numeric variables.
Bare except and Its Limitations
A bare except is an except clause without a specified exception type:
try:
age = int(input("Age: "))
except:
print("Invalid input")
This catches exceptions broadly. Although it may appear convenient, broad handling can hide unrelated programming mistakes and make debugging harder. It is not a good choice for ordinary expected-input validation because the intended problem is specifically invalid integer text.
Prefer a specific handler:
try:
age = int(input("Age: "))
except ValueError:
print("Please enter a whole number.")
Specific exception handling is the next important step after learning the basic structure. See catching specific exceptions for more patterns.
Introducing try...except...else
An optional else clause can follow try and except. It runs only when the entire try suite finishes without raising an exception.
try:
age = int(input("How old are you? "))
except ValueError:
print("Please enter a whole number.")
else:
print("Your input was converted successfully.")
if age >= 18:
print("You meet the age requirement.")
else:
print("You do not meet the age requirement.")
The except path is for failure: it responds when conversion raises ValueError. The else path is for success: it contains work that should happen only after conversion succeeds. This separation makes it clear which statements depend on a valid integer.
Do not confuse this else clause with the else belonging to an if statement. The try statement's else means that no exception occurred; the conditional statement's else means that its condition was false.
For the full form and later cleanup behavior, continue with try...except...else statements and try...except...finally statements.
Troubleshooting Common Problems
The program stops after letters are entered
Cause: int() cannot convert the supplied text and raises ValueError.
Fix: Put the conversion in a try block and handle ValueError with a clear response.
Later statements inside try do not run
Cause: An earlier statement raised an exception, so the remaining statements in that try suite were skipped.
Fix: Identify the failing statement. Put only the operation that may fail in try, and organize success-only work in else.
A broad handler hides bugs
Cause: A bare except captures more than the intended invalid-input condition.
Fix: Catch the expected type, such as ValueError for invalid integer conversion.
try or except reports an indentation or syntax problem
Cause: The clauses are not aligned, or one of their suites is not indented.
Fix: Align except with try, and indent at least one statement beneath each clause.
The age comparison fails after input processing
Cause: The comparison is attempted before successful conversion, or the age variable was not assigned because conversion failed.
Fix: Convert inside try and put the comparison in else so it runs only after conversion succeeds.
Exam-Relevant Summary
- An exception is a runtime event that interrupts normal execution.
- An unhandled exception produces a traceback and stops the affected flow.
- The
tryblock contains code that might raise an exception. - The matching
exceptsuite contains fallback or recovery behavior. - If the try suite succeeds, its except suite is skipped.
- If a statement fails, later statements in that try suite do not run for that attempt.
int()raisesValueErrorwhen supplied text has an invalid integer format.- A specific handler such as
except ValueError:is preferable to a bareexcept:for expected input validation. - A try statement's
elsesuite runs only when the try suite completes without an exception.