Exceptions give expected failures a clear path.
A bug is an error in program logic. An exception is a runtime event Python can report and your program can handle. For an order, invalid input and missing stock are expected situations worth handling precisely.
stock = 3
quantity = 5
try:
if quantity > stock:
raise ValueError("not enough stock")
except ValueError as error:
print(error)
else:
print("Order accepted")
finally:
print("Order check finished")try contains code that may fail. except handles a matching exception, else runs only when no exception happens, and finally always runs. Catch specific types rather than using a bare except or broad except Exception.
not enough stock
Order check finishedUse raise when your code detects invalid business data. A custom exception such as InvalidQuantityError makes the reason clear. Use raise NewError(...) from error when a lower-level error is the cause.
Keep errors useful: Do not hide unexpected failures. Handle only exceptions you understand, show a useful message, and let unrelated problems remain visible while developing.
class InvalidQuantityError(ValueError):
pass
class OutOfStockError(Exception):
pass
def validate_order(quantity, stock):
if quantity <= 0:
raise InvalidQuantityError("quantity must be positive")
if quantity > stock:
raise OutOfStockError("not enough stock")
return quantityCustom exceptions describe the shop rule that failed. Multiple except branches can then show the right response for each case.
try:
validate_order(quantity, stock)
except InvalidQuantityError:
print("Choose a positive quantity")
except OutOfStockError:
print("Choose fewer items")The first matching except branch runs. Order specific exceptions before broader parent types.
try:
quantity = int(text_quantity)
except ValueError as error:
raise InvalidQuantityError("quantity must be a number") from errorraise ... from ... keeps the original conversion error connected to the clearer shop-level exception.
Trace one order check
- 1. Enter tryPython attempts the validation code.
- 2. Raise when a rule failsA non-positive quantity or insufficient stock stops normal execution.
- 3. Match exceptThe matching exception branch gives the learner or customer a useful response.
- 4. Finish clearlyelse runs after success; finally runs whether the order succeeded or failed.
Common mistakes
- Catching everythingAvoid bare except and broad except Exception when a specific type explains the problem.
- Using else after a failureelse belongs to try and runs only when no exception was raised.
- Forgetting finallyUse finally for work that must finish, such as logging or closing a resource.
- Raising without a clear ruleRaise a meaningful exception when validation detects invalid quantity or stock.
