What Exceptions Are
In this tutorial, we'll understand runtime errors and why programs stop.
An exception is an error that happens while a program is running.
This code has no syntax problem:
number = int("hello")
But it fails when it runs, because "hello" cannot be converted into an integer.
Python raises an exception:
ValueError
Exceptions Stop the Program
By default, an unhandled exception stops your program:
age = int(input("Age: "))
print("Next birthday:", age + 1)
If the user types ten, Python cannot convert it with int(), so the program stops before the second line finishes.
Common Exception Types
You will see these often:
ValueError: a value has the right type but the wrong contentTypeError: an operation does not make sense for the types involvedZeroDivisionError: code tried to divide by zeroIndexError: a list index does not existKeyError: a dictionary key does not exist
Example:
numbers = [10, 20]
print(numbers[5])
This raises IndexError.
Exceptions Are Useful
Exceptions are not just annoying messages. They tell you exactly what went wrong and where to look.
When building real programs, you can handle expected exceptions and give the user a better message.
Practice
Run three small programs that cause ValueError, ZeroDivisionError, and IndexError. Read each traceback and find the line number.