Python Basics

Python Try Except: Handling Errors with Examples

Stop one bad input from crashing your program. Catch the errors you expect and always clean up with finally.

  • Beginner
  • 2 min read
  • 1 runnable example
What you'll learn
  • try, except, else and finally
  • Catching specific exceptions such as ValueError
  • Raising your own errors
int("abc")
  1. 1try: int(text)Python tries the risky line
  2. 2except ValueError:The error is caught
  3. 3finally:Clean-up runs either way
Without except, the ValueError would stop the program.

The paths through try / except

The problem

Some things can fail even in correct code: a user types "abc" where a number is expected, a file is missing, a network call times out. Without handling, the program stops with a long error. You want to react calmly instead: show a clear message, use a default, try again.

Think of it like this

try / except is like a safety net under a trapeze artist. The act runs normally in the try part. If the artist slips, the net (except) catches that fall and the show goes on. finally is the bow at the end that happens whether the act succeeded or not.

From a safety net to code
try:🎪 Try the risky move
except ValueError:🕸️ The net for this kind of fall
print("Please provide a valid integer")🙂 Recover with a clear message
finally:🙇 Always happens at the end
Catch the errors you expect, and let real bugs show.
In one sentence

try runs code that might fail; if an exception of the type named in except happens, Python runs that block instead of stopping, and finally runs in every case.

Key points

  1. int(value) fails because "not-a-number" is not digits, so print(number) inside try never runs.
  2. except ValueError: catches exactly that kind of error and prints a friendly message.
  3. finally: runs whether the conversion worked or not, so "Conversion finished" is always printed.
  4. Name the error type you expect; a bare except: would also hide real bugs.

When should you use it?

  • Converting user input that might not be valid.
  • Reading files or calling web services that might be unavailable.
  • Cleaning up (closing a file, a connection) even when something went wrong.

When not to use it

  • Checking something you can test simply, such as an empty list: an if is clearer.
  • Hiding a bug: catching every error makes the program continue with wrong data.

Example code

Run code →
main.py
value = "not-a-number"

try:
    number = int(value)
    print(number)
except ValueError:
    print("Please provide a valid integer")
finally:
    print("Conversion finished")
Get a Run button for this example

Result of running the code

Please provide a valid integer
Conversion finished

Code explanation

The except clause handles a specific conversion error. Finally runs whether conversion succeeds or fails.

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Change the input and predict the output before running.
  2. Handle empty or invalid input.
  3. Wrap the logic in a function and add more test cases.
Run in the Python compiler →

Python try and except at a glance

try: ... except ValueError: ...Run code and handle one kind of error
except (ValueError, TypeError):Handle several kinds of error the same way
except ValueError as error:Get the error object, for example to print its message
else:Runs only when the try block raised no error
finally:Always runs, error or not (good for cleanup)
raise ValueError("Age must be positive")Raise an error yourself
raiseInside except: re-raise the current error
class OutOfStock(Exception): passDefine your own exception type
with open("data.txt") as f:Close the file automatically, even when an error happens

Common mistakes with try and except

A bare except that catches everything

except: also catches KeyboardInterrupt and real bugs, which hides problems. Catch the errors you expect.

Problem
try:
    age = int(text)
except:
    age = 0
Fix
try:
    age = int(text)
except ValueError:
    age = 0

Silently ignoring errors

except Exception: pass throws away the error, so nothing tells you what went wrong. At least log or print it.

Problem
try:
    save(report)
except Exception:
    pass
Fix
try:
    save(report)
except OSError as error:
    print(f"Could not save the report: {error}")

Catching the general error before the specific one

except blocks are checked in order, so a broad Exception first means the specific block never runs.

Problem
try:
    value = int("abc")
except Exception:
    print("Something failed")
except ValueError:
    print("Not a number")  # never reached
Fix
try:
    value = int("abc")
except ValueError:
    print("Not a number")
except Exception:
    print("Something failed")

Frequently asked questions

What is the difference between except, else and finally?

except runs when the try block raises a matching error, else runs when it raises no error, and finally always runs at the end, which makes it the place for cleanup.

How do I catch multiple exceptions in Python?

List them in a tuple, except (ValueError, KeyError):, to handle them the same way, or write several except blocks to handle each one differently.

How do I print the error message?

Name the error with as: except ValueError as error: print(error). Use traceback.print_exc() to see the full traceback.

How do I create my own exception?

Define a class that inherits from Exception, such as class OutOfStock(Exception): pass, then raise it with raise OutOfStock("No more pears").

Finished this lesson?

Mark it as learned to track your progress.

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges