Try and Except

Try and Except

Some errors are not bugs — they are situations. Text from outside the program might not be a number; a file might not exist. try/except handles such a situation instead of stopping the program.

An error that stops the program is called an exception. int("abc") raises the exception ValueError:

int("abc")

Output:

ValueError: invalid literal for int() with base 10: 'abc'

Wrapped in try/except, the failure is handled:

try:
    count = int("abc")
    print("converted")
except ValueError:
    count = 0
    print("not a number, using 0")

print(count)

Output:

not a number, using 0
0

Python runs the try block. The moment a ValueError is raised, the rest of the try block is skipped — "converted" never printed — and the except block runs instead. If nothing goes wrong, the except block is skipped.

The name after except says which exception to handle. Any other exception passes through untouched, which is what you want: handle what you expect, let real bugs surface.

Exercise

  1. Define a function named to_number with one parameter, text.
  2. It returns int(text). When the conversion raises ValueError, it returns None instead.

to_number("42") returns 42. to_number("4.5") returns Noneint rejects it.

Run your code to see the output, then press Submit.

Tests

import unittest


class TestToNumber(unittest.TestCase):
    def test_valid_number(self):
        self.assertEqual(to_number("42"), 42)

    def test_negative_number(self):
        self.assertEqual(to_number("-7"), -7)

    def test_letters_give_none(self):
        self.assertIsNone(to_number("abc"))

    def test_decimal_text_gives_none(self):
        self.assertIsNone(to_number("4.5"))
def to_number(text):
    try:
        return int(text)
    except ValueError:
        return None


print(to_number("42"))
print(to_number("abc"))
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.