VMware ESXi and vSphere Cluster Management
Python try...except...else Statements
Learn how Python's try...except...else statement works, when else runs, how to validate input with ValueError, and why success code belongs in else.
Python exception handling lets a program respond to runtime problems instead of stopping immediately. An exception is a runtime event that interrupts normal execution, such as trying to convert the text "abc" to an integer.
A try...except...else statement separates two paths:
- The
trysuite contains an operation that might fail. - An
exceptclause handles a matching exception. - The optional
elsesuite contains normal success-path code that should run only if thetrysuite finishes without an exception.
This separation keeps exception-handling code distinct from code that should run after successful work.
Basic syntax and block structure
The general structure is:
try:
risky_operation()
except SomeError:
handle_the_error()
else:
continue_after_success()
You can use more than one except clause:
try:
risky_operation()
except FirstError:
handle_first_error()
except SecondError:
handle_second_error()
else:
continue_after_success()
try,except, andelseare aligned at the same indentation level.- Statements belonging to each suite are indented consistently beneath its clause.
- The
elseclause follows allexceptclauses. elseis optional and cannot be used by itself; it must follow atrystatement.
Here, except is not Python's conditional if...else. It is an exception handler, while this else is a success branch for the try operation.
How execution flows
Python first runs the try suite. The result determines what happens next:
| What happens in try | Does except run? | Does else run? | Result |
|---|---|---|---|
| Try completes normally | No | Yes | Python continues with the else suite. |
| Try raises a matching exception | Yes | No | The matching handler runs, then execution continues after the complete statement. |
| Try raises an unmatched exception | No matching handler | No | The exception propagates outward to another handler or terminates the program. |
| Else itself raises an exception | Not the preceding except clauses | Already entered | The new exception must be handled by an enclosing or separate appropriate handler. |
An except clause handles only matching exceptions raised while Python is executing the try suite. It does not automatically handle errors raised later in else.
Using specific exception types
A specific exception type describes the failure you expect. For invalid integer input, use ValueError. This exception occurs when a value has an appropriate general form for an operation but cannot be interpreted as required, as with int("abc").
try:
number = int("abc")
except ValueError:
print("That was not an integer.")
Targeted handlers are safer and clearer than a bare except:. A bare except catches nearly every exception, including system-level exceptions such as KeyboardInterrupt and SystemExit. It can therefore hide a user's request to stop a program or conceal an important failure.
except Exception: is a broad alternative that generally excludes those system-exiting exceptions, but it can still hide programming bugs. Use it only when a broad application-level recovery policy is genuinely intended. For input conversion, catch ValueError instead.
Example: validating an age entry
The conversion is the operation expected to raise ValueError. The age comparison belongs in else because it requires a successfully converted integer.
try:
age = int(input("Enter your age: "))
except ValueError:
print("Enter a whole-number age.")
else:
if age <= 21:
print("Not eligible.")
else:
print("Eligible.")
Possible outcomes are:
- Input such as
sixteenraisesValueError. Theexceptsuite prints the error message, andelseis skipped. - Input such as
18converts successfully. Theelsesuite runs and printsNot eligible.. - Input such as
25converts successfully. Theelsesuite runs and printsEligible..
Why not put all later code in try?
You could put the comparison inside try, but that makes the protected region larger than necessary:
try:
age = int(input("Enter your age: "))
if age <= 21:
print("Not eligible.")
else:
print("Eligible.")
except ValueError:
print("Enter a whole-number age.")
This version may work, but keeping only the conversion in try has advantages:
- It limits the code that is expected to raise the anticipated exception.
- It reduces the chance that an unrelated programming bug is mistaken for invalid input.
- It clearly separates failure handling from successful continuation.
- It makes the dependency visible: the comparison runs only after conversion succeeds.
Example: division after numeric conversion
The same pattern works when later processing depends on successful conversion. If division occurs in else, remember that division-related errors are not handled by the conversion handler.
try:
total = float(input("Enter the total: "))
people = int(input("Enter the number of people: "))
except ValueError:
print("Enter valid numeric values.")
else:
share = total / people
print(f"Each person pays {share:.2f}.")
If people is zero, total / people raises ZeroDivisionError inside else. The preceding except ValueError does not catch it. Handle that case separately when it is part of the program's expected input conditions:
try:
total = float(input("Enter the total: "))
people = int(input("Enter the number of people: "))
except ValueError:
print("Enter valid numeric values.")
else:
try:
share = total / people
except ZeroDivisionError:
print("The number of people must be greater than zero.")
else:
print(f"Each person pays {share:.2f}.")
Example: processing a file only after it opens
else is also useful when a file must be opened and read before its contents can be processed.
try:
with open("scores.txt", "r", encoding="utf-8") as file:
data = file.read()
except FileNotFoundError:
print("The scores file was not found.")
else:
scores = [int(item) for item in data.split()]
print(f"Read {len(scores)} scores.")
The FileNotFoundError handler deals with failure to find the file. Processing happens only after opening and reading succeed. However, an error raised while converting a file item to an integer occurs in else, so it is not handled by the preceding except FileNotFoundError.
Relationship to other try forms
| Clause | When it runs | Typical role |
|---|---|---|
try | First, while its suite is executed | Run an operation that may raise an exception. |
except | When a matching exception occurs in try | Recover from or report a specific failure. |
else | Only when try completes without an exception | Run normal success-path processing. |
finally | Whether try succeeds or fails | Perform cleanup or other actions that must occur. |
A simple try...except handles errors:
try:
operation()
except SomeError:
recover()
A try...except...else statement adds a dedicated success branch:
try:
operation()
except SomeError:
recover()
else:
continue_after_success()
finally is different from else. The success branch runs only when try succeeds, while cleanup in finally runs whether the operation succeeds or fails. When all forms are used, the conceptual order is try, one or more except clauses, else, then finally:
try:
operation()
except SomeError:
recover()
else:
continue_after_success()
finally:
clean_up()
Common problems and fixes
The else suite runs, but a later statement fails
The try suite finished successfully, so Python correctly entered else. The later failure occurred inside else, where the preceding except clauses do not apply. Handle the later operation with its own suitable try...except structure if needed.
Invalid text input is not handled
int() raises ValueError for text such as "hello". Put the conversion inside try and catch ValueError around that conversion.
A broad except hides unrelated bugs
An except: clause or overly broad handler may catch failures beyond the expected conversion problem. Replace it with the narrowest relevant type, such as except ValueError:.
Code needs the converted value after conversion failed
If conversion fails, the assignment may not produce a usable value and else will not run. Put code that depends on the converted value in else, or stop, return, or continue from the error path.
Adding else causes a SyntaxError
Check that else is aligned with try and follows every except clause. The valid order is try, except clauses, optional else, and optional finally.
Summary
- Use
tryfor the operation that may raise an expected exception. - Use a specific
excepttype, such asValueError, to handle the expected failure. - Use
elsefor code that should run only after the entiretrysuite succeeds. - An unmatched exception propagates, and
elsedoes not run. - Exceptions raised inside
elseneed their own or an enclosing handler. - Use
finallyfor actions that must run regardless of success or failure.