✦ Python Intermediate & OOP Intermediate Python

L2 · Concept 04 · Advanced Python Techniques

Handle errors.
Protect the order.

A small online shop can respond clearly when an order has an invalid quantity or not enough stock.

Learning goalUse precise try, except, else, finally, and raise blocks to validate an order safely.
01 Learn02 Try03 Predict

Learning as a guest

Learning as a guest? Save your progress!

Create a free account to learn with Sloby AI, check your understanding, and track your progress.

The entire platform is free throughout 2026. Foundations stays free forever.

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 finished

Use 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.

Order validation
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 quantity

Custom exceptions describe the shop rule that failed. Multiple except branches can then show the right response for each case.

Different exceptions, different help
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.

Preserve the cause
try:
    quantity = int(text_quantity)
except ValueError as error:
    raise InvalidQuantityError("quantity must be a number") from error

raise ... from ... keeps the original conversion error connected to the clearer shop-level exception.

Trace one order check

  1. 1. Enter tryPython attempts the validation code.
  2. 2. Raise when a rule failsA non-positive quantity or insufficient stock stops normal execution.
  3. 3. Match exceptThe matching exception branch gives the learner or customer a useful response.
  4. 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.

Python Playground

Loading Python runtime…

Change quantity or stock to explore successful orders, invalid quantities, and unavailable stock.

order_handling.pyPython
OutputWaiting for Python
The browser runtime is loading. You can still edit the example code.

Pyodide runs Python in a browser Web Worker. It is stopped and restarted if code keeps running. Browser execution is not a complete security boundary; do not enter secrets or rely on it for untrusted code isolation.

Which lines will this program print?

Follow the raised exception. Notice that else does not run after an exception, but finally does.

def validate_quantity(quantity, stock):
    if quantity <= 0:
        raise ValueError("quantity must be positive")
    if quantity > stock:
        raise RuntimeError("not enough stock")
    return quantity

try:
    validate_quantity(5, 3)
except RuntimeError:
    print("Out of stock")
else:
    print("Order accepted")
finally:
    print("Order check finished")
Choose the output

Practice independently

Mini Challenge — Process an order

Complete a small order validator without hiding the reason an order cannot be accepted.

Your goalRaise one exception for a non-positive quantity and another for insufficient stock. Handle both with separate except branches.

order_challenge.py

Optional hints
  • Check quantity before stock, because a non-positive quantity is invalid regardless of availability.
  • Inside each failing if branch, use raise followed by the appropriate exception class and a short message.
Ask Sloby for a hint
Sloby, the Python AI Tutor mascot

Your learning mentor

Sign in to ask Sloby

Create a free account or sign in to get AI guidance while you learn.

Sign in to check your understanding

Create a free account or sign in to receive AI feedback and save your learning progress.

Python AI Tutor · Learn by understanding, not just by running code.