Lesson 20 of 30

In progress

Course progress

Python

Handle errors with try and except

Catch the errors you can recover from, let the rest through, and keep input loops from crashing on bad text.

A program that crashes on the first bad input is a demo, not a tool. Error handling is how you decide which failures are recoverable and which should stop everything loudly.

What you will learn

  • Wrap risky work in try and catch specific exceptions.
  • Use else, finally and raise deliberately.
  • Validate input in a loop instead of crashing.

Catch what you can fix

int("hello") raises ValueError. Wrapping the conversion lets you respond instead of dying.

Code
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.



Press Run to see the output.

The try block holds only the lines that can fail. A broad try that wraps half the program hides which operation actually raised, and makes the handler guess.

Catch the specific exception you expect. except ValueError documents the failure and lets unexpected errors surface with their real traceback.

A loop that survives bad input

The practical pattern is to keep asking until the conversion succeeds. continue sends the loop back for another attempt.

Code
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.



Press Run to see the output.

Validation is split into two checks: conversion errors and range errors. Both send the learner back to the prompt without a traceback, and the function returns only a value that passed both.

input() inside the browser runner is limited, so on this page the example is illustrative; run it in a local terminal to type answers.

else and finally

else runs when the try block finished without an exception, and finally runs either way.

Code
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.



Press Run to see the output.

Use else for code that should run only on success, so it is not accidentally protected by the try. Use finally for cleanup that must happen regardless: closing a file, releasing a lock, hiding a spinner.

Raising your own errors

Sometimes the right response is to stop. raise with a clear message turns a silent bad state into a visible failure.

Code
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.



Press Run to see the output.

as error binds the exception so you can print its message. Raising ValueError for a bad value is idiomatic; define your own exception class later when callers need to distinguish your errors from built-in ones.

When a program has several failure modes, a small custom exception makes them catchable without matching on message text:

Code
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.



Press Run to see the output.

The class body is deliberately empty; the name is the information. Callers can now catch InsufficientFunds without accidentally catching an unrelated ValueError from somewhere else in the same block.

Do not swallow errors

An empty except: catches everything, including KeyboardInterrupt and typos in your own code. It makes bugs invisible, which is worse than a crash.

try:
risky()
except:
pass

If you truly need a catch-all, log it and re-raise. Otherwise catch the narrow exceptions you can actually handle, and let the rest produce a traceback you can read. A useful test: if you cannot describe in one sentence why this error is safe to ignore, you should not be catching it.

A bare except: around a large block also catches NameError from a misspelled variable. The program appears to work, the feature silently does nothing, and the real bug stays hidden for days. Catch ValueError, KeyError or ZeroDivisionError specifically, and keep the try block short.

Write safe_divide(a, b) that returns the result, or None with a printed message when b is zero. Then write a loop that asks for two numbers and prints the result, recovering from both non-numeric input and division by zero.

Show solution
Code
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.



Press Run to see the output.

safe_divide handles its own failure and returns a value the caller can check. The loop handles conversion separately, so each error has one owner.

Recap

  • try guards the risky lines; except names the specific failure you can handle.
  • else runs on success, finally always runs.
  • raise with a clear message beats returning a silent None; never use a bare except.

You have finished functions and errors. Next, you will model data with classes, so behaviour lives next to the values it changes.

Should I use try/except or check first?
Both are valid. Checking is clearer when the condition is easy to test, such as a missing key with `get`. Catching is better when the failure is rare or the check would duplicate work. Python’s culture leans toward trying and handling.
Can I catch several exceptions at once?
Yes: `except (ValueError, TypeError) as error:` handles either and binds the exception. Keep the tuple short and related; a long list usually means the try block is doing too much.

Progress is saved in this browser only. No account, no email.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated November 16, 2026.