Catching an error
After this: Catch one kind of error so that the program carries on, and say when not to.
On this page · 7 sections · 4 checks
A form on a website asks for your age. You type abc by mistake. A good form does not break. It says "please type a number" and lets you try again. The program behind the form met the same error as lesson 1's int("abc"), but it had a plan for it.
An error you can catch
So far an error has always stopped the program. The other way to see an error is as an : something the failing line raises, which the program can catch and deal with. The names you met in lesson 1, ValueErrorNumberFormatException and the others, are the kinds of exception.
To catch one, you put the lines that might fail in a try block, and under it you write what to do if they do fail, with the kind of error named. In Python the second part starts with except; in Java it starts with catch.
Work through the program below, where text holds abc:
- Line 24 starts the
tryblock. Nothing happens yet; it only marks the lines that are being watched. - Line 35 tries to turn
abcinto a number and fails. Instead of stopping, the program looks for a matching exceptcatch line. - The line names the right kind, so the program jumps there. The rest of the
tryblock, the print ofGot, is skipped. - The exceptcatch lines run:
Not a number: abcis printed. - The program carries on with the line after the whole thing, and prints
Carrying on.
- Run the programRun it and step through. The conversion line fails, but no message stops the program: watch the marker jump past the rest of the try block, into the except lines (catch in Java), and then carry on below.
text = "abc"try: number = int(text) print("Got " + str(number))except ValueError: print("Not a number: " + text)print("Carrying on")run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
In the trace the failing line raises no red message. The band narrates a jump into the exceptcatch lines instead, and the program ends as any program does.
The code
text = "abc"try: number = int(text) print("Got " + str(number))except ValueError: print("Not a number: " + text)print("Carrying on")Not a number: abc Carrying on
public class Main { public static void main(String[] args) { String text = "abc"; try { int number = Integer.parseInt(text); System.out.println("Got " + number); } catch (NumberFormatException e) { System.out.println("Not a number: " + text); } System.out.println("Carrying on"); }}Not a number: abc Carrying on
Keep asking until it works
A form asks again after a bad answer. Taking text from the keyboard belongs to the next tutorial, so this program has a list of three attempts instead, abc, x and 42, and a loop that goes through them until one converts.
attempts = ["abc", "x", "42"]number = 0for text in attempts: try: number = int(text) break except ValueError: print("Not a number: " + text)print(number)run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
The first two attempts fail, are caught, and print a line each. The third converts, number becomes 42, and break ends the loop. The last line prints 42.
The rule
Name the kind of error you expect, around the lines where you expect it. When that kind is raised in the try block, the rest of the block is skipped, the exceptcatch lines run, and the program carries on. Any other kind still stops the program with its message, which is what you want: a message for a bug you did not expect is a gift, not a nuisance.
Run it
Change abc to 12 and run again: nothing fails, the exceptcatch lines are skipped, and Got 12 is printed instead.
Check yourself
A line inside a try block fails with the kind of error the exceptcatch line names. What happens?
This time the text is digits. What does this print?
text = "15"try: number = int(text) print(number + 1)except ValueError: print("Not a number")print("Done")public class Main { public static void main(String[] args) { String text = "15"; try { int number = Integer.parseInt(text); System.out.println(number + 1); } catch (NumberFormatException e) { System.out.println("Not a number"); } System.out.println("Done"); }}The text 7x is not a number. Complete the missing line so that the error is caught and the program prints Not a number and then Done. Write the whole line, including the colon at the endbrackets and the opening brace.
text = "7x"try: number = int(text) print(number)____________________ # ← catch the conversion error print("Not a number")print("Done")public class Main { public static void main(String[] args) { String text = "7x"; try { int number = Integer.parseInt(text); System.out.println(number); } ____________________ // ← catch the conversion error System.out.println("Not a number"); } System.out.println("Done"); }}A programmer wraps a whole 40-line program in one try block with except:catch (Exception e) that prints Something went wrong. Why is that almost always a bad idea?
Honesty notes
- Say what an exception is: an error seen as a thing the program can catch instead of stopping.
- Write a try block with one except line (one catch line in Java) that names the kind of error you expect.
- Say what happens when the error comes: the rest of the try block is skipped, the except lines run, and the program carries on after them.
- Keep asking until a value is right, with a loop around a try block.
- Say why catching everything is almost always wrong: it hides the message that would have told you where the bug is.