Lesson · Python for Beginners

Errors, exceptions, and validation

An error message is evidence about what the program tried to do and where it stopped.

What you will learn

  • Recognize a ValueError
  • Use try/except for expected invalid input
  • Avoid hiding unrelated failures

Read the exception

A traceback shows the sequence of calls that led to a failure and ends with the exception type and message. Start at the last line to identify what went wrong, then inspect the relevant line in your code. A ValueError often means the type was acceptable but the supplied value was not.

Validate at the boundary

User input is not guaranteed to match the format a program expects. Put conversion close to where text enters the program and give a helpful response when conversion fails. Validation is not about distrusting the learner; it is about making the program's requirements explicit.

Catch a specific failure

A try block contains the operation that may fail, and an except clause names the failure the program can recover from. Catching Exception broadly can hide programming mistakes unrelated to the expected input problem. Keep the protected block small so a handler does not accidentally swallow a different failure.

Make recovery visible

After catching a known exception, explain what input was expected or ask for another value. The example uses a fixed invalid string to make the behavior repeatable. In an interactive program, a loop can offer another attempt; do not report success when the operation did not succeed.

Keep the original cause visible

A handler should tell the learner what happened and what a valid next step looks like. It should not return a made-up value that lets later code pretend the conversion succeeded. When an error cannot be handled safely at that level, let it propagate so the caller or developer can address it with the context they have.

Python example
text = 'twenty'
try:
    age = int(text)
except ValueError:
    print('Please enter a whole number.')
Expected output
Please enter a whole number.

Practice exercise

Convert the text '4.5' to an integer and print a clear message when conversion fails.

Show a hint

int('4.5') raises ValueError; catch that specific exception.

Show one possible solution

Wrap int('4.5') in try/except ValueError and print a message such as 'Enter a whole number.' in the handler.

Quick check

Which exception is raised by int('hello')?

Frequently asked questions

Should I catch every exception?
<p>Usually not. Catch the specific error your program can handle. Broad handlers can conceal bugs and make a failed operation appear successful.</p>