VMware ESXi and vSphere Cluster Management
Python try...except Statements: Handling Exceptions
Learn how Python try...except statements handle runtime errors, including invalid age input, ValueError, execution flow, and common limitations.
When a Python program runs, most statements follow the expected path. Sometimes an operation cannot be completed, such as converting letters to an integer. Python reports this situation as an exception.
What Is an Exception?
An exception is a runtime event or error that interrupts normal program execution. A runtime error happens while the program is running, after Python has started executing its statements.
For example, int() creates an integer from a compatible value or string. Converting the string '42' works, but converting 'forty-two' does not:
age = int('forty-two')
This operation raises a ValueError. A ValueError occurs when an operation receives a value of a generally appropriate type but unacceptable content. If the exception is not handled, Python stops the affected program and displays a traceback, which is diagnostic output showing where the unhandled exception occurred.
Exception handling is the process of detecting an exception and responding to it in code. Instead of allowing an anticipated failure to terminate the program with a traceback, you can provide a useful response, such as an invalid-input message.
Why Use try...except?
A try...except statement separates two related parts of a program:
- The try block contains operations that might raise an exception.
- The except clause contains the response when an exception is caught.
This lets a program handle anticipated runtime failures rather than terminate unexpectedly. The handler might display an explanation, use a fallback value, or allow the program to continue.
Basic try...except Syntax
try:
# Code that might raise an exception
risky_operation()
except:
# Recovery or user-facing response
print('Something went wrong.')
The try line must be followed by an indented block. The except clause must follow that block and also has its own indented block. Python uses indentation to identify which statements belong to each block.
Put the smallest reasonable section of potentially failing code inside try. Put recovery, fallback behavior, or a user-facing error message inside except.
Execution Flow
- Python begins executing the statements in the
tryblock. - If every statement finishes successfully, Python skips the
exceptblock. - If an exception occurs, Python stops executing the remaining relevant statements in the
tryblock. - Python looks for a matching exception handler and runs its
exceptblock. - After successful handling, execution can continue with the statement after the complete
try...exceptconstruct.
| Condition in the try block | What Python does | Whether except runs | Program result |
|---|---|---|---|
| No exception occurs | Finishes the try block and skips the handler | No | Normal execution continues afterward |
| An exception occurs during integer conversion | Stops the remaining try statements and begins matching exception handling | Yes, if the handler matches | The program can show a friendly response and continue |
Example: Checking Age Eligibility
This example asks for an age, converts the response to an integer, and uses an if/else statement to make an age-based decision.
age = int(input('Enter your age: '))
if age >= 18:
print('You are eligible.')
else:
print('You are not eligible yet.')
If the user enters 25, input() returns the string '25', int() converts it to the integer 25, and the program prints You are eligible. If the user enters 15, the conversion succeeds and the other branch runs.
What Happens with Nonnumeric Input?
If the user enters twenty, the input is a string that cannot be converted to an integer. The conversion raises ValueError:
age = int(input('Enter your age: '))
if age >= 18:
print('You are eligible.')
else:
print('You are not eligible yet.')
With no handler, Python reports an unhandled ValueError and displays a traceback. The conditional statement is never reached because execution stops at the failed conversion.
Protecting the Conversion with try...except
try:
age = int(input('Enter your age: '))
if age >= 18:
print('You are eligible.')
else:
print('You are not eligible yet.')
except ValueError:
print('Please enter your age as a whole number.')
print('Program continues here.')
For numeric input, the conversion and age decision run normally, and the except block is skipped. For input such as twenty, int() raises ValueError, the remaining statements in the try block are skipped, and the friendly message is printed. The final statement can then run.
This example names ValueError because that is the expected failure from converting unsuitable text with int(). Handling a specific exception is safer than catching unrelated failures.
Bare except Limitations
An except clause without a named exception catches broadly:
try:
age = int(input('Enter your age: '))
except:
print('Invalid input.')
This may appear convenient, but it is generally poor practice for real programs. A bare except can catch almost every exception, including errors that are unrelated to user input. It can hide programming bugs and make diagnosis harder because the traceback is replaced by a vague message.
The preferred next step is to name the expected exception:
try:
age = int(input('Enter your age: '))
except ValueError:
print('Please enter a whole number.')
Specific handlers make the program's intended recovery behavior clearer. Later, you can learn about multiple except clauses, exception objects with as, and retry loops for repeated input.
Exceptions, Syntax Errors, and Logic Errors
Not every kind of mistake is an exception that a basic try...except statement can solve.
| Category | When it occurs | Can basic try...except handle it? | Example |
|---|---|---|---|
| Runtime exception | While valid Python code is running | Yes, when the handler matches the exception | int('twenty') raises ValueError |
| Syntax error | Before ordinary execution, when Python cannot parse the code structure | Generally no; fix the invalid code | A missing colon after an if statement |
| Logical error | When the program runs but its instructions produce an unintended result | No; correct the program's logic | Using > when the intended test was >= |
A syntax error is invalid Python structure detected before normal execution, such as incorrect punctuation or indentation. A logical error is a flaw in the intended algorithm; the program may run successfully while producing the wrong answer. try...except is for runtime exceptions, not a general solution for syntax mistakes or incorrect logic.
Troubleshooting
The program stops after letters are entered for an age
Cause: int() cannot convert the text into an integer, so it raises ValueError.
Resolution: Place the conversion in a try block and handle ValueError in an except clause.
The error-message handler does not run
Cause: No exception occurred, so Python correctly skipped the except block. Another possibility is that the risky statement is not indented inside try.
Resolution: Test with input that cannot be converted, such as abc, and check the indentation.
A broad handler hides an unexpected bug
Cause: A bare except catches more than the intended input-conversion failure.
Resolution: Handle the expected specific exception, such as ValueError, instead.
try...except does not fix invalid Python syntax
Cause: Syntax errors are detected before the affected code can execute normally.
Resolution: Correct the code structure, punctuation, or indentation.
Key Points
- An exception interrupts normal execution while a program is running.
try...exceptlets a program respond to expected runtime failures instead of ending with an unhandled traceback.- Statements in the
tryblock run first; a matchingexceptblock runs only when an exception occurs. ValueErroris appropriate for invalid content passed toint(), such as nonnumeric age input.- Prefer specific exception types over a bare
except. - Syntax errors require code correction, and logical errors require correcting the program's reasoning; neither is solved by using
try...exceptas a general-purpose fix.
Continue learning with Python try...except statements and related exception-handling techniques.