Errors in a program are of two kinds. A syntax error is found before the program runs, because the code breaks the rules of the language. An exception is an error that happens while the program is running, even though the code is correct.

What is an Exception?

When an error occurs during execution, Python creates an exception object and stops the normal flow. If nothing handles it, the program ends and prints a traceback, which shows where the error happened and its type. Common exceptions are ZeroDivisionError for division by zero, ValueError for an invalid value such as int("abc"), TypeError for an unsuitable type, IndexError for an index outside a list, KeyError for a missing dictionary key, and FileNotFoundError for a missing file.

Definition: Exception. An error that occurs while a program is running and that interrupts its normal flow unless it is handled.

The try-except Block

The code that might fail is placed in a try block. If an exception occurs in it, the rest of the block is skipped and Python looks for a matching except block. If one is found, its code runs and the program continues after the whole structure. A specific exception type should be named, as in except ZeroDivisionError. Several except blocks can follow one try, and one block can catch several types by listing them in a tuple. The form except Exception as e gives access to the error object, so that its message can be printed.

Why Handle Exceptions?

Handling lets a program recover, for example by asking the user to enter a number again, and it allows important resources to be released. A program that handles its errors is more reliable and gives clear messages instead of a long traceback. However, errors should be caught only where something sensible can be done about them.

Table 4.1: Common built-in exceptions

Exception Cause Example
ZeroDivisionError Division by zero 5 / 0
ValueError Right type, wrong value int("abc")
TypeError Wrong type "5" + 5
IndexError Index out of range [1, 2][5]
KeyError Missing key {}["a"]
FileNotFoundError File absent open("x.txt")

Example 4.1: Handling division by zero

Problem: Write a program that divides two numbers and handles division by zero and invalid input.

Solution:

  1. Put the input and division inside a try block.
  2. Add an except block for ZeroDivisionError and another for ValueError.

Result: With the input 8 and 0 the program prints a message instead of stopping.

try:
    a = int(input("a: "))
    b = int(input("b: "))
    print("Result:", a / b)
except ZeroDivisionError:
    print("Cannot divide by zero")
except ValueError:
    print("Please enter integers only")
print("Program continues")

Input

8
0

Output

a: b: Cannot divide by zero
Program continues

Common mistakes

  • Using a bare except that hides every error, including mistakes in the program.
  • Putting too much code in the try block, so that the real cause is unclear.
  • Placing a general except Exception before a specific one, which makes the specific block unreachable.

Key takeaways

  • An exception is a run-time error, unlike a syntax error.
  • try holds risky code and except handles the error.
  • Name the specific exception that is expected.
  • except Exception as e gives the error message.

Practice questions

  1. What is an exception?
  2. Which exception is raised by int("abc")?
  3. What is the purpose of the try block?

Answers to the practice questions

  1. An error that occurs while a program is running.
  2. ValueError.
  3. It holds the code that may cause an exception.

Sources

  • Official BCA syllabus Python Programming, course code 26BCA403SEC01, Unit IV