VMware ESXi and vSphere Cluster Management
Catch Specific Exceptions in Python
Learn how to catch specific Python exceptions with ValueError, KeyboardInterrupt, separate handlers, grouped exception tuples, and try/except/else.
An exception is an event raised while a program is running that interrupts normal control flow. Python provides built-in exception classes, such as ValueError and KeyboardInterrupt, to describe different problems.
Specific exception handling means catching only named exception classes that your program expects and knows how to address. This produces clearer messages, safer recovery behavior, and fewer hidden programming errors.
Why Catch Exceptions Specifically?
A broad catch-all handler can hide unrelated errors. For example, a handler that catches every exception might make a misspelled variable, an incorrect calculation, or a genuine programming bug look like ordinary invalid user input.
try:
age = int(input("Enter your age: "))
except:
print("Something went wrong.")
This handler does not explain which problem occurred or whether the program can recover. It may also conceal bugs that should be fixed rather than ignored.
Instead, target the error the program expects:
try:
age = int(input("Enter your age: "))
except ValueError:
print("Please enter your age as a whole number.")
Now the program handles invalid numeric text meaningfully. Unrelated exceptions remain visible, which makes unexpected failures easier to diagnose during development.
The try and except Structure
A try block is the code region monitored for exceptions. An except clause names a handler that runs when a matching exception is raised.
try:
# Code that might raise an exception
value = int(input("Enter a value: "))
except ValueError:
# Code that handles invalid integer text
print("Enter a valid whole number.")
If the conversion raises ValueError, normal execution stops at the failing statement and transfers to the matching handler. If no exception occurs, the statements after the try statement continue normally.
Catching ValueError from Numeric Conversion
int() converts suitable text to an integer. If the text is not a valid integer, Python raises the built-in ValueError exception. For example, converting "twenty" with int() is invalid.
try:
age = int(input("Enter your age: "))
except ValueError:
print("Invalid age. Enter a whole number, such as 20.")
The conversion belongs inside the try block because it is the operation that might raise ValueError. The message in the handler tells the user how to correct the input.
Using else for Successful Input
A try statement can have an else clause. The else block runs only when the try block completes without raising an exception. This makes it a useful place for logic that depends on successful conversion.
try:
age = int(input("Enter your age: "))
except ValueError:
print("Invalid age. Enter a whole number.")
else:
if age < 21:
print("You are below the age threshold.")
else:
print("You meet the age threshold.")
There are now two clearly separated paths:
- Error path: invalid text raises
ValueError, so the except block displays a validation message. - Success path: conversion succeeds, so the else block checks whether the age is below 21 or is at least 21.
The age comparison should not run after a failed conversion because no valid integer age was produced.
Unmatched Exceptions Remain Unhandled
An except ValueError clause catches only ValueError and compatible exception types. It does not catch unrelated exceptions.
When a user presses Ctrl+C during interactive input, Python typically raises KeyboardInterrupt. A ValueError handler does not match it. The exception continues upward through the program and may end the program if no other handler catches it.
try:
age = int(input("Enter your age: "))
except ValueError:
print("Please enter a whole number.")
else:
print(age)
In this example, invalid text is handled, but Ctrl+C is not. That behavior can be appropriate when interruption should stop the program, or you can add a specific handler when a friendlier response is required.
Multiple Specific except Clauses
Use separate handlers when different exception types need different messages or recovery actions. Python checks handlers in written order and uses the first matching handler.
try:
age = int(input("Enter your age: "))
except ValueError:
print("That was not a valid whole number.")
except KeyboardInterrupt:
print("Input was interrupted with Ctrl+C.")
else:
if age < 21:
print("You are below the age threshold.")
else:
print("You meet the age threshold.")
The ValueError handler gives input guidance, while the KeyboardInterrupt handler explains that the user interrupted the prompt. Each handler has a response suited to its exception.
Catching Several Exception Types in One Handler
If several exception types require exactly the same response, place them in an exception tuple: a parenthesized, comma-separated collection of exception classes.
try:
age = int(input("Enter your age: "))
except (ValueError, KeyboardInterrupt):
print("Unable to read an age.")
else:
if age < 21:
print("You are below the age threshold.")
else:
print("You meet the age threshold.")
The tuple tells Python that the one handler should match either ValueError or KeyboardInterrupt. Grouping is concise, but it is less informative when the two cases need different guidance.
| Handler style | Syntax pattern | Best use case | Result |
|---|---|---|---|
| Separate except clauses | except ValueError:except KeyboardInterrupt: | Each exception needs a different message or recovery action. | Each matching type receives its own response. |
| One except clause with an exception tuple | except (ValueError, KeyboardInterrupt): | Several exception types should receive the same response. | One shared handler processes all listed types. |
Input and Exception-Handling Outcomes
| User action or input | Result of conversion or input operation | Exception raised | Handler that runs | Whether else runs | Program response |
|---|---|---|---|---|---|
Valid age below threshold, such as 18 | int() returns 18 | None | None | Yes | The program reports that the person is below 21. |
Valid age at or above threshold, such as 21 or 25 | int() returns the integer | None | None | Yes | The program reports that the person meets the threshold. |
Non-numeric input, such as abc | int() cannot convert the text | ValueError | except ValueError | No | The program asks for a valid whole number. |
| Ctrl+C during the prompt | The interactive input is interrupted | KeyboardInterrupt | except KeyboardInterrupt, if present | No | A separate handler can explain the interruption; otherwise it may end the program. |
Complete Age Example
This version uses separate handlers so invalid text and interruption receive different responses.
try:
age = int(input("Enter your age: "))
except ValueError:
print("Invalid age. Enter a whole number, such as 20.")
except KeyboardInterrupt:
print("\nAge entry was interrupted.")
else:
if age < 21:
print("You are below the age threshold.")
else:
print("You meet the age threshold.")
Troubleshooting
Text input terminates the program during int()
If text such as abc causes a traceback, the conversion is not surrounded by a handler for ValueError. Put the int() call in the try block and add except ValueError.
Age-checking logic runs after invalid input
Logic that depends on a successful conversion may be placed outside the correct control flow, or a fallback value may be used without validation. Put success-only age logic in the try statement's else block.
Ctrl+C is not handled by except ValueError
KeyboardInterrupt is a different exception class. Add except KeyboardInterrupt, or include it in an exception tuple when the response should be identical to the ValueError response.
Different exceptions receive the same generic response
A grouped handler is being used even though the cases require different actions. Replace it with separate except clauses.
Unexpected bugs seem to disappear
An overly broad handler may be catching errors that were not anticipated. Narrow the handler to expected exception types and allow unrelated errors to remain visible while developing.
Key Points
- Use
tryfor code that might raise an exception. - Use
except ExceptionTypeto handle a particular expected exception. ValueErrorcommonly occurs when invalid text is passed toint().- Use
elsefor code that should run only after the try block succeeds. except ValueErrordoes not catchKeyboardInterruptor other unrelated exceptions.- Use separate handlers for different responses and an exception tuple for one shared response.
- Specific handlers make recovery clearer and prevent unrelated programming errors from being hidden.
For continued practice, return to catching specific exceptions in Python and modify the age example with your own validation messages.