I1 · Python Programming for AI

Handling Exceptions

Exception handling lets a program respond to an error instead of crashing. Code that might fail goes in a try block; except blocks handle specific error types; else runs if no error happened; and finally always runs, error or not, often to clean up.

8 min Intermediate · Sublevel Beginner Jump to the activity

What you need: The earlier topics of this module.

Definition

What should a calculator do when someone divides by zero?

Exception handling lets a program respond to an error instead of crashing. Code that might fail goes in a try block; except blocks handle specific error types; else runs if no error happened; and finally always runs, error or not, often to clean up.

In simple words

try is 'attempt this'. except ZeroDivisionError is 'if it fails this way, do this instead'. A good program tells the user what went wrong in plain words and keeps going, instead of showing a scary traceback and stopping.

Overview

  • An exception is an error that happens while a program runs, such as dividing by zero or a missing file.
  • Unhandled, an exception stops the program and prints a traceback.
  • try ... except catches an exception so the program can respond and continue.
  • Exceptions form a hierarchy: ValueError and ZeroDivisionError are both kinds of Exception.
  • Catch specific exceptions, never a bare except:, which also hides real bugs.
  • Good handling gives users clear messages instead of crashes, which matters in every deployed AI app.

Why it matters

Real data is messy and real users make mistakes. Programs that read files, call web APIs or talk to LLMs must handle failures such as missing files, bad numbers and network errors, or they break at the worst moment.

Key terms

Exception
An error raised while a program runs, which stops it unless handled.
try block
Code that might raise an exception.
except block
Code that runs when a matching exception occurs.
finally
A block that always runs, error or not, often for cleanup.
raise
A statement that deliberately triggers an exception.
Exception hierarchy
The family tree of error types; catching a parent type also catches its children.

Types

Python provides several building blocks for handling exceptions. Each type of clause has its own job.

1. try-except

Runs risky code in try and handles a named error in except.

  • How it works: If an exception occurs in try, Python jumps to the matching except; if none occurs, except is skipped.
  • Example: try: age = int(input()) except ValueError: print("Please type a number").
  • When to use it: Use it around any operation that can fail for reasons outside your control, such as user input or files.

2. Multiple and grouped except clauses

Several except blocks for different errors, or one block for a tuple of errors.

  • How it works: Python checks the clauses from top to bottom and runs the first that matches; except (ValueError, TypeError) as e: handles both and keeps the message in e.
  • Example: except FileNotFoundError: ... except PermissionError: ... when opening a file.
  • When to use it: Use it when different failures need different responses; put specific exceptions before general ones.

3. else clause

A block that runs only if the try block finished without any exception.

  • How it works: It keeps the code that depends on success separate from the code being protected.
  • Example: try: value = int(text) except ValueError: ... else: total += value.
  • When to use it: Use it to make clear which line you expect might fail.

4. finally clause

A block that always runs, whether or not an exception happened.

  • How it works: Python runs finally after try, except and else, even if there was a return or an unhandled error.
  • Example: finally: connection.close() to release a database connection.
  • When to use it: Use it for clean-up: closing files and connections or releasing resources (with-blocks often do this for you).

5. raise

A statement that creates an exception on purpose.

  • How it works: raise ValueError("message") stops normal flow and passes the error to the caller; a bare raise inside except re-raises the current error.
  • Example: if marks < 0: raise ValueError("Marks cannot be negative").
  • When to use it: Use it to reject invalid input early, at the point where the problem is detected.

6. Custom exceptions

Your own exception classes, made by inheriting from Exception.

  • How it works: class InvalidRollNumber(Exception): pass creates a new error type that callers can catch by name.
  • Example: A library raising InsufficientDataError when a model is trained on too few rows.
  • When to use it: Use them in larger programs and libraries so that callers can handle your specific failures.

Explained in detail

Expect the unexpected

Programs meet a messy world: users type words where numbers are expected, files go missing, networks drop, a server returns nonsense. Exception handling lets a program respond sensibly instead of crashing. You put the risky code in a try block and say what to do in an except block for each kind of error you expect. If no error happens, the except blocks are skipped. If one happens, Python jumps straight to the matching except, skipping the rest of the try block.

The full shape

PartRuns whenTypical use
tryAlways firstThe operation that might fail
except ValueErrorThat error type occurredAsk again, use a default or log a message
except (KeyError, IndexError)Any of several typesHandle related errors the same way
elseNo error occurredCode that should run only on success
finallyAlways, lastClose connections, release resources

Common built-in exceptions

  • ValueError: right type, wrong value, as in int("abc").
  • TypeError: an operation on the wrong type, as in 5 + "5".
  • KeyError and IndexError: a missing dictionary key or list position.
  • FileNotFoundError: the file is not where you said.
  • ZeroDivisionError: dividing by zero.

Handling errors well

Catch only the errors you expect and know how to handle. A bare except: or except Exception: that swallows everything hides real bugs: a typo in a variable name becomes a silent wrong answer instead of a clear NameError. Keep the try block small, wrapping only the line that can fail, so you do not accidentally catch errors from elsewhere. When you do catch an error, do something meaningful, such as showing a helpful message or using a safe default, and never just pass silently without at least logging it.

You can also raise exceptions yourself. A function that receives a mark of 150 can raise ValueError("mark must be between 0 and 100") instead of returning a nonsense grade. Failing loudly and early, close to the cause, is far easier to debug than a wrong value that travels through the program and causes trouble much later. AI pipelines rely on this: a data loader that raises an error on a corrupted row is better than one that quietly trains a model on garbage.

How it works

try:
    risky step
except ValueError:
    handle bad input
except ZeroDivisionError:
    handle division by zero
else:
    runs only if nothing failed
finally:
    always runs

In code

A calculator that never crashes: each bad case gets a clear message.

safe_calculator.py
def divide(a_text, b_text):
    try:
        a = float(a_text)
        b = float(b_text)
        result = a / b
    except ValueError:
        return "Please type numbers only"
    except ZeroDivisionError:
        return "Can't divide by zero"
    else:
        return f"{a} / {b} = {result:.2f}"
    finally:
        print("  (checked", a_text, "and", b_text + ")")

for pair in [("10", "4"), ("10", "0"), ("ten", "2")]:
    print(divide(*pair))

Output

  (checked 10 and 4)
10.0 / 4.0 = 2.50
  (checked 10 and 0)
Can't divide by zero
  (checked ten and 2)
Please type numbers only

Try it yourself

Which block runs, and when?

For divide("10", "4"), which succeeds, put the blocks in the order they run.

  1. 1The function returns the message
  2. 2finally: print the 'checked' note
  3. 3else: build the result message
  4. 4try: convert both and divide

Common mistakes

  • Catching every error with a bare except.
  • Putting too much code in try, so you can't tell which line failed.
  • Silently ignoring errors with pass. At least report what happened.

Check yourself

Question 1

1. When does finally run?

Question 2

2. float("abc") raises…

Question 3

3. When does else run in a try statement?

Summary

  • try runs risky code; except handles specific errors.
  • else runs on success; finally always runs.
  • Catch specific errors and give users clear messages.

Finished reading?

Sources: Python docs: Handling Exceptions