A customer writes the quantity as "two" instead of "2". Your program runs int("two"), then stops completely with a ValueError. The next customer can't be served, only because of one word.
An error like that, which appears while a program is running, is called an exception. try/except is the way to catch it, so the program does not stop. Picture two cashiers at Mr. Darto's stall. The rigid cashier is a program with no try/except: faced with writing that cannot be read, this cashier does not know what to do and stops serving. The good cashier is a program with try/except. This cashier has a backup plan: "try to read the number; if I can't, ask the customer to write it again". Then the cashier continues with the next customer. In code, the "try" part goes in try, and the "if I can't" part goes in except.
Reading a traceback
This is the program from the story of the customer who wrote "two":
text = "two"
quantity = int(text)
print("Total:", 15 * quantity)
The program stops, and Python prints an error report called a traceback:
Traceback (most recent call last):
File "/home/darto/stall.py", line 2, in <module>
quantity = int(text)
ValueError: invalid literal for int() with base 10: 'two'
- Read a traceback from the bottom. The last line holds the exception's type (
ValueError) and its message. This message means:int()cannot turn'two'into a number. - Above it are the file name, the line number and the line of code that failed.
- The program stops at the line that failed, line 2. Line 3 never runs.
The exception types you will see most often:
ValueError: the value is wrong, for exampleint("two").TypeError: the type is wrong, for example"Total: " + 15or10 / "abc".ZeroDivisionError: division by zero.KeyError: a dictionary key that does not exist.IndexError: a list index out of range.FileNotFoundError: a file that does not exist.
try and except
Wrap the line that can fail in try, and write the backup plan in except:
text = "two"
try:
quantity = int(text)
print("Total:", 15 * quantity)
except ValueError:
print("Quantity must be a number, not", text)
print("Cashier keeps serving")
The result depends on what text holds:
text |
What happens | Output |
|---|---|---|
"3" |
the try block runs to the end, except is skipped |
Total: 45, then Cashier keeps serving |
"two" |
int(text) fails, the rest of try is skipped, except ValueError runs |
Quantity must be a number, not two, then Cashier keeps serving |
try:holds the code to attempt. As soon as one line in it raises an exception (the line fails and produces an error), the rest of thetryblock is skipped.except ValueError:catches that type of exception only, then runs its block. The program does not stop, so the last line still runs.except ValueError as e:keeps the exception in the variablee.print("Failed:", e)prints its message:Failed: invalid literal for int() with base 10: 'two'.- Catch a specific type.
except Exception:or justexcept:catches every exception, including the ones caused by typos in your own code. As a result, you never find those typos. - In a real program,
textusually comes frominput(), which always returns astr(see the lesson Variables & Data Types). A user can type anything, soint()can fail. That is whyint(input("How many glasses? "))is almost always wrapped intry.
You can also write try inside a function. There, an except block may use return to give back a replacement value:
def per_person(total, people):
try:
return total // people
except ZeroDivisionError:
return "Number of people can't be 0"
print(per_person(45, 3)) # 15
print(per_person(45, 0)) # Number of people can't be 0
This function uses //, not /. Remember from the operators lesson: / always gives a float. 10 / 2 is 5.0, while 45 // 3 is 15.
Several excepts, else and finally
Some customers want to split the bill: a total of $45 is shared equally among a number of people. The cashier types the number of people as text, and this program works out each person's share:
total = 45
text = "3"
try:
people = int(text)
per_person = total // people
except ValueError:
print("Number of people must be a number, not", text)
except ZeroDivisionError:
print("Number of people can't be 0")
else:
print("Pay per person:", per_person)
finally:
print("Cashier ready again")
The result for three values of text:
text |
What happens | Output |
|---|---|---|
"3" |
try succeeds, so else runs |
Pay per person: 15, Cashier ready again |
"two" |
int fails: ValueError |
Number of people must be a number, not two, Cashier ready again |
"0" |
45 // 0 fails: ZeroDivisionError |
Number of people can't be 0, Cashier ready again |
- Python compares the type of the exception that appeared with each
except, from top to bottom. The firstexceptthat matches runs, and the rest are skipped. - To catch two exception types with the same block, write both in one
except, in brackets:except (ValueError, ZeroDivisionError) as e:, withprint("Invalid number of people:", e)in its block. Whentextholds"0", this printsInvalid number of people: integer division or modulo by zero. else:runs only whentryfinishes without an exception. Put code there that should run only when everything worked.finally:always runs: on success, when the exception was caught, and even when it was not caught.finallyis the place for clean-up, such as closing a file or closing the connection to a database.- The order is fixed:
try,except,else,finally. Python refuses anelsewith noexcept:SyntaxError: expected 'except' or 'finally' block. - A quick example: the
tryblock holdsquantity = int("3"),except ValueError:printsnot a number,else:printsquantity: 3andfinally:printsdone.int("3")succeeds, soexceptis skipped. Two lines are printed:quantity: 3, thendone.
Now suppose except ZeroDivisionError is removed and text is "0". No except catches the ZeroDivisionError that appears, but finally still runs first. Only after that does the program stop:
Cashier ready again
Traceback (most recent call last):
File "/home/darto/stall.py", line 6, in <module>
per_person = total // people
~~~~~~^^~~~~~~~
ZeroDivisionError: integer division or modulo by zero
raise and your own exceptions
Your own code can raise an exception too, with raise. In this example even the exception type is our own, OutOfStock:
class OutOfStock(Exception):
pass
def take_toast(stock):
if stock == 0:
raise OutOfStock("toast is sold out")
return stock - 1
try:
take_toast(0)
except OutOfStock as e:
print("Sorry,", e) # Sorry, toast is sold out
raiseraises an exception on purpose. The text in its round brackets becomes the exception's message. The type can be a built-in one, for exampleraise ValueError("price cannot be negative"), as in the setter from the property lesson.- Your own exception is a child class of
Exception. This is inheritance, from the inheritance lesson.passis enough as the body of the class. - An exception with a clear name such as
OutOfStockcan be caught separately from other errors. If that function is called without atry, the program stops, and the last line of the traceback isOutOfStock: toast is sold out.
⚠️ An except that catches too much, and a misunderstood finally
- Catching everything.
except Exception:also catches errors caused by typos. For example,people = int(txet)(textmistyped) raisesNameError, but the cashier program still prints "Number of people must be a number". The bug (a mistake in the code) stays hidden. Catch only the type you actually expect. - A
tryblock that is too long. Put only the lines that can fail intry. Move the rest toelse, so exceptions from other lines are not caught silently. - Guessing what
/gives.10 / 2is5.0, not5. For whole-number division, use//. - Forgetting that
finallyalways runs. Do not put code infinallyif it should run only on success. It belongs inelse.
TL;DR: An exception is an error that appears while a program runs. Read a traceback (Python's error report) from the bottom: the exception's type and message, then the file and line. try: holds the code to attempt, and except SomeError: catches that type so the program continues. as e keeps that exception, with its message, in the variable e. Several except blocks are matched from the top. else runs only when try raised no exception, and finally always runs. The order is try, except, else, finally. For example, when try holds int("abc") and there are except ValueError and finally blocks, the message from the except block is printed, then the message from the finally block. raise raises an exception on purpose, and your own exception type is a child class of Exception, such as class OutOfStock(Exception). Catch specific types, not every exception.
⚡ Read a traceback from the bottom
Meaning: An error that appears while a program runs is called an exception. Python then prints a report called a traceback. The last line of a traceback holds the exception's type and its message, for example ValueError: invalid literal for int() with base 10: 'two'. Above it are the file name, the line number and the line that failed. The program stops at that line.
⚡ Try first, catch it if it fails
Write:
text = "two"
try:
quantity = int(text)
print("Total:", 15 * quantity)
except ValueError:
print("Quantity must be a number, not", text)
print("Cashier keeps serving")
Guess first: does the line print("Total:", ...) inside try run?
No. As soon as int(text) fails, the rest of the try block is skipped and the except block runs.
Meaning: try: holds the code to attempt. except ValueError: catches an exception of the type ValueError, so the program doesn't stop and the last line still runs. Catch a specific type, not every exception.
⚡ else and finally
Guess first: a finally block is written last, after every except. When an exception isn't caught by any except, does the finally block still run?
It does. finally runs first, and only then does the program stop.
Meaning: else runs only when try finishes with no exception. finally always runs, so it is the place for clean-up, such as closing a file. The order is try, except, else, finally.
⚡ Raising your own exception
Write:
class OutOfStock(Exception):
pass
def take_toast(stock):
if stock == 0:
raise OutOfStock("toast is sold out")
return stock - 1
try:
take_toast(0)
except OutOfStock as e:
print("Sorry,", e) # Sorry, toast is sold out
Meaning: raise raises an exception on purpose, and the text in its round brackets becomes the message. Your own exception is a child class of Exception. as e keeps that exception, with its message, in e.