Basic error handling in Python with try and except
Once you understand functions, the next important step in beginner Python is learning how to deal with errors in a controlled way. Up to this point, many example programs have assumed that everything goes right. The user enters valid input, calculations work, files exist, and values have the expected type. In real programs, that is rarely true all the time. People type letters where numbers are expected, files may be missing, and invalid operations can cause a program to stop unexpectedly. This is exactly why error handling matters.
Python provides a clear and beginner-friendly system for handling many common runtime errors. The most important tools at this stage are try and except. They allow your program to attempt an operation and then respond safely if something goes wrong. Instead of crashing, the program can display a message, ask for new input, or continue in a controlled way.
This lesson explains basic error handling in Python with try and except in a simple, practical way. You will learn what an exception is, how try and except work, why error handling matters, what common beginner examples look like, and which mistakes to avoid.
What is an error in Python
An error is a problem that prevents Python from executing code normally. Some errors happen before the program even starts properly, while others happen during execution.
For beginners, the most important category here is the runtime error. This is an error that happens while the program is running.
Example:
print(10 / number)
This may work, but it can also fail in at least two ways:
- if the user types text instead of a valid number
- if the user enters
0, which causes division by zero
Without error handling, the program stops and shows an error message.
That is where try and except become useful.
What is an exception in Python
In Python, many runtime errors are represented as exceptions. An exception is Python’s way of signaling that something unexpected happened during execution.
Examples of common beginner exceptions include:
ValueErrorZeroDivisionErrorTypeErrorIndexErrorKeyErrorFileNotFoundError
Each one represents a different kind of problem.
For example:
- converting
"hello"tointraisesValueError - dividing by zero raises
ZeroDivisionError - accessing a missing list index raises
IndexError
At beginner level, the exact names matter less than understanding the main idea: an exception means the normal flow of the program was interrupted by an error condition.
Why error handling matters
Without error handling, a small mistake can stop the entire program.
For example:
print(“Next year you will be”, age + 1)
If the user enters 25, everything works.
If the user enters twenty-five, the program crashes.
That is a poor user experience, and it also makes the program less reliable.
Error handling helps because it allows your code to:
- prevent abrupt crashes
- show clearer messages
- recover from invalid input
- keep running when appropriate
- guide the user to correct the problem
- make scripts more robust
For beginners, this is one of the first steps toward writing code that behaves well in real-world conditions.
The basic idea of try and except
The structure is simple:
code_that_might_fail
except:
code_that_runs_if_there_is_an_error
Python first runs the code inside the try block.
- if no error happens, Python skips the
exceptblock - if an error happens, Python stops the
tryblock and jumps toexcept
Basic example:
number = int(input(“Enter a number: “))
print(“You entered:”, number)
except:
print(“That was not a valid number”)
If the user enters a valid integer, the program prints it.
If the user enters invalid text, the except block runs instead.
This is the core pattern of beginner error handling.
A simple try and except example
One of the most common beginner examples is numeric input.
age = int(input(“Enter your age: “))
print(“Next year you will be”, age + 1)
except:
print(“Please enter a valid whole number”)
This is much safer than a version without try and except.
What happens:
- Python tries to convert the input to an integer
- if that works, the program continues normally
- if conversion fails, Python goes to the
exceptblock
This is a practical example because invalid input is extremely common in real programs.
How control flow works with try and except
It helps to understand the flow step by step.
Example:
number = int(input(“Enter a number: “))
result = 10 / number
print(result)
except:
print(“Something went wrong”)
Possible flow:
If the user enters 2
int(input(...))works10 / numberworksprint(result)runsexceptis skipped
If the user enters 0
int(input(...))works10 / numberfails with division by zero- Python jumps to
except print(result)is not completed
If the user enters hello
int(input(...))fails- Python jumps to
except - the rest of the
tryblock is skipped
This is important:
when an exception happens inside try, the remaining lines in that try block are skipped
Catching specific exceptions
A plain except: works, but in most cases it is better to catch specific exceptions.
Example:
number = int(input(“Enter a number: “))
print(10 / number)
except ValueError:
print(“That was not a valid whole number”)
except ZeroDivisionError:
print(“You cannot divide by zero”)
This version is better because it distinguishes between two different errors.
- invalid number input
- division by zero
That makes the feedback clearer and the code more precise.
For beginners, this is a very good habit to build early: catch the kind of error you actually expect.
ValueError explained
ValueError happens when a function receives a value of the right general type, but the content is invalid for the operation.
A classic beginner case is this:
This fails because int() expects text that represents an integer, such as "25", not "hello".
With error handling:
number = int(input(“Enter a whole number: “))
print(“Number:”, number)
except ValueError:
print(“That input is not a valid integer”)
This is one of the most common uses of try and except in beginner Python.
ZeroDivisionError explained
ZeroDivisionError happens when you try to divide by zero.
Example:
This is not allowed mathematically, so Python raises an exception.
Safe version:
number = int(input(“Enter a number: “))
print(10 / number)
except ZeroDivisionError:
print(“Division by zero is not allowed”)
This allows the program to fail gracefully instead of crashing.
Using multiple except blocks
A single try block can have more than one except.
Example:
number = int(input(“Enter a number: “))
print(100 / number)
except ValueError:
print(“Please enter a valid integer”)
except ZeroDivisionError:
print(“Zero is not allowed here”)
This is useful because a single piece of code may fail for different reasons.
Each except block handles one kind of problem.
Python checks them in order and runs the first matching one.
Using one except block for multiple exception types
You can also handle multiple specific exceptions together.
Example:
number = int(input(“Enter a number: “))
print(100 / number)
except (ValueError, ZeroDivisionError):
print(“Invalid input or division by zero”)
This is shorter, but less specific in its feedback.
For beginners, separate except blocks are often easier to understand, especially while learning.
Catching the exception object
Sometimes you want to see the actual error message. You can capture the exception object using as.
Example:
number = int(input(“Enter a number: “))
print(10 / number)
except Exception as error:
print(“An error occurred:”, error)
This prints the exception message itself.
At beginner level, this is useful for learning and debugging, but you should not rely on Exception for everything in normal code if you can catch more specific exceptions instead.
Why bare except is often not ideal
A plain except: catches almost anything, which may seem convenient, but it can also hide problems you did not expect.
Example:
number = int(input(“Enter a number: “))
print(10 / number)
except:
print(“Something went wrong”)
This works, but it gives no detail about what failed.
A better version is:
number = int(input(“Enter a number: “))
print(10 / number)
except ValueError:
print(“Please enter a valid integer”)
except ZeroDivisionError:
print(“Division by zero is not allowed”)
This is clearer, safer, and easier to debug.
For beginners, the simple rule is:
- plain
except:is acceptable for very basic learning examples - specific exceptions are usually better in real code
The else block with try and except
Python also allows an else block after except. This runs only if no exception occurs.
Example:
number = int(input(“Enter a number: “))
except ValueError:
print(“Invalid input”)
else:
print(“You entered:”, number)
Flow:
- if conversion fails,
exceptruns - if conversion succeeds,
elseruns
This can make code cleaner because it separates the success path from the error path.
Another example:
number = int(input(“Enter a number: “))
result = 100 / number
except ValueError:
print(“Please enter a valid integer”)
except ZeroDivisionError:
print(“Zero is not allowed”)
else:
print(“Result:”, result)
This is a good structure when you want the successful result handling to be clearly separated.
The finally block in Python
Python also supports finally. This block always runs, whether an exception happened or not.
Example:
number = int(input(“Enter a number: “))
print(10 / number)
except ValueError:
print(“Invalid number”)
except ZeroDivisionError:
print(“Cannot divide by zero”)
finally:
print(“Program section finished”)
No matter what the user enters, the finally block runs.
At beginner level, finally is useful to know about, especially because it is often used with files and cleanup tasks later.
A practical input validation loop with try and except
One of the best beginner uses of error handling is repeated input until the user provides valid data.
Example:
try:
age = int(input(“Enter your age: “))
break
except ValueError:
print(“Please enter a valid whole number”)print(“Your age is”, age)
This is an excellent beginner pattern because it combines:
whiletryexceptbreak
The logic is:
- keep asking for input
- if conversion works, exit the loop
- if conversion fails, show an error and try again
This is much more realistic than letting the program crash.
Error handling with lists
Exceptions are not only about user input. Lists can also cause runtime errors.
Example:
print(numbers[5])
This raises IndexError because the list has no item at index 5.
Safe version:
numbers = [10, 20, 30]
try:
print(numbers[5])
except IndexError:
print(“That index does not exist”)
This is a good beginner example because it shows that exceptions can happen in many parts of Python, not just numeric conversion.
Error handling with dictionaries
Dictionaries can also raise exceptions, especially when a missing key is accessed directly.
Example:
print(person[“age”])
This raises KeyError.
Safe version:
person = {“name”: “Alice”}
try:
print(person[“age”])
except KeyError:
print(“That key does not exist”)
In practice, get() is often a cleaner solution for optional dictionary keys, but this is still a useful way to understand dictionary-related exceptions.
Error handling with files
A very common real-world example is trying to open a file that does not exist.
Example:
content = file.read()
This raises FileNotFoundError.
Safe version:
with open(“missing.txt”, “r”) as file:
content = file.read()
print(content)
except FileNotFoundError:
print(“The file was not found”)
This is one reason error handling becomes increasingly important as Python programs move beyond toy examples.
Common beginner mistakes with try and except
Several problems appear often when beginners first learn error handling.
Using except without understanding the actual error
Some beginners write except: around everything without knowing what may fail.
That can hide important mistakes and make debugging harder.
Better approach: identify the expected exception if possible.
Putting too much code inside try
Example:
number = int(input(“Enter a number: “))
print(“Starting calculation”)
result = 100 / number
print(“Done”)
except:
print(“Error”)
This works, but the try block is broader than necessary.
Cleaner approach:
number = int(input(“Enter a number: “))
result = 100 / number
except ValueError:
print(“Invalid number”)
except ZeroDivisionError:
print(“Cannot divide by zero”)
else:
print(“Starting calculation”)
print(result)
print(“Done”)
In general, keep the try block focused on the code that may actually fail.
Catching the wrong exception type
Example:
number = int(input(“Enter a number: “))
except ZeroDivisionError:
print(“Wrong handler”)
This does not handle invalid numeric input properly because int() conversion errors raise ValueError, not ZeroDivisionError.
Forgetting that the rest of try is skipped after an error
Example:
number = int(“hello”)
print(“This line never runs”)
except ValueError:
print(“Conversion failed”)
Once the exception happens, Python jumps out of the try block immediately.
Using try and except to hide logic problems
Error handling is for unexpected runtime problems, not for avoiding proper logic design. For example, if you already know a list index may be missing, sometimes it is better to check the length first rather than always relying on exceptions.
Practical beginner examples
Example 1: Safe integer input
number = int(input(“Enter a whole number: “))
print(“You entered:”, number)
except ValueError:
print(“That was not a valid integer”)
Example 2: Safe division
number = int(input(“Enter a divisor: “))
print(100 / number)
except ValueError:
print(“Please enter a valid integer”)
except ZeroDivisionError:
print(“You cannot divide by zero”)
Example 3: Safe list access
items = [“apple”, “banana”, “orange”]
try:
print(items[5])
except IndexError:
print(“List index is out of range”)
Example 4: Safe dictionary access
user = {“name”: “Emma”}
try:
print(user[“age”])
except KeyError:
print(“Key not found”)
Example 5: Repeat until valid input
try:
value = float(input(“Enter a price: “))
print(“Price accepted:”, value)
break
except ValueError:
print(“Please enter a valid number”)
These are all practical beginner examples that reflect real Python usage.
Why try and except make beginner code better
At the beginning of learning Python, many examples are very idealized. But real users do not always follow instructions perfectly, and real environments are not always predictable. Error handling helps close that gap.
With try and except, beginner code becomes:
- safer
- more user-friendly
- more realistic
- easier to recover from invalid input
- less likely to stop abruptly
This is one of the first steps from demonstration code toward actual usable programs.
Good beginner habits with error handling
A few habits make your try and except code much better.
Catch specific exceptions when possible
Prefer:
over a blanket except: when you know what you expect.
Keep try blocks focused
Only place the risky code inside try.
Give helpful messages
The message should explain what went wrong in a useful way.
Bad:
Better:
Use loops for retry behavior
If the user can correct the problem, combine try and except with a loop.
Do not hide unexpected bugs too aggressively
If everything is wrapped in broad except blocks, real programming mistakes can become harder to notice.
What you should understand before moving on
Before continuing to the next lesson, you should be comfortable with the following:
- runtime errors in Python are often exceptions
tryruns code that may failexcepthandles errors if they happen- specific exceptions such as
ValueErrorandZeroDivisionErrorare better than a generic catch-all in many cases elseruns only when no exception occursfinallyruns whether there is an error or not- after an exception, the rest of the
tryblock is skipped tryandexceptare especially useful for input validation and safer user interaction
If these ideas are clear, the next lesson on reading and writing files in Python will be much easier, because file handling is one of the most common practical areas where exceptions matter.
Basic error handling in Python with try and except allows a program to respond safely when something goes wrong during execution. Instead of crashing on invalid input, division by zero, missing files, or invalid indexes, the program can show a clearer message and continue in a controlled way.
Image(s) used in this article are either AI-generated or sourced from royalty-free platforms like Pixabay or Pexels.
This article may contain affiliate links. If you purchase through these links, we may earn a commission at no extra cost to you.
Get the weekly RF & IT briefing
Radio guides, RF calculators, AI, Windows, Linux and satellite communication explainers. One useful email per week. No spam.
