๐Ÿ“˜ CodingMarble Learn

Exception Handling in Python: Catch the Error, Keep the Program Alive

A syntax error stops a program before it runs. An exception is an error that happens while it runs, such as dividing by zero or opening a missing file. Without handling, the program crashes. With try and except, Python catches the exception and runs your rescue code instead. else runs when no exception happened; finally runs every time, error or not. raise lets you throw an exception yourself.

๐ŸŽฌ Step-by-step story

  1. A program runs line by line. A bad line (like 10 / 0) throws an exception. With no net, the program crashes.
  2. Put risky lines inside try. When an exception is thrown, Python stops the try block and drops into the except net.
  3. Each except catches one type of error, like a labelled net: ZeroDivisionError, ValueError. The first matching net catches it.
  4. else runs only when try finished with no error. finally runs every time, error or not, so it is used to clean up.
  5. raise lets you throw an exception yourself when data is wrong, like a negative age.
  6. Your turn: type a divisor. Watch which blocks light up: try, except, else, finally.

Tip: drag the 3D scene to turn it. Use two fingers to zoom.

๐Ÿค” Common doubts, cleared

Is a syntax error an exception?

They are different. A syntax error is found before running, so the program never starts. An exception happens during the run.

Do the lines after the error inside try still run?

No. At the error Python leaves the try block at once and jumps to except.

What if no except matches the error?

The exception is not caught. finally still runs, then the program crashes with a traceback.

What is the difference between else and finally?

else runs only when there was no error. finally runs every time.

Why would I raise an error myself?

When the input is legal Python but wrong for your program, like age = -5. raise stops it with a clear message.

Syntax errors and exceptions

A syntax error is a mistake in the rules of writing Python, like a missing colon: if x > 5. Python finds it before running and the program does not start.

An exception is an error that happens while the program runs, even though the code is written correctly. For example print(10 / n) is fine when n = 2, but fails when n = 0. When an exception is raised (thrown) and nobody catches it, Python stops the program and prints a traceback.

Common built-in exceptions

try and except

try:
    n = int(input('Number: '))
    print(100 / n)
except ZeroDivisionError:
    print('Cannot divide by zero')
except ValueError:
    print('Please type digits only')

else and finally

The full shape is try โ†’ except โ†’ else โ†’ finally.

try:
    f = open('marks.txt')
except FileNotFoundError:
    print('File missing')
else:
    print(f.read())
    f.close()
finally:
    print('Done')

Raising an exception yourself

raise throws an exception on purpose when the data is wrong.

age = int(input('Age: '))
if age < 0:
    raise ValueError('Age cannot be negative')

assert is a quick check: assert age >= 0, 'bad age' raises AssertionError if the condition is False.

Try it: break your own program

Write a small program that asks for two numbers and divides them. Run it and type 0, then type 'abc'. Note the name of each exception in the traceback. Now wrap the code in try with one except for each, add a finally that prints 'Thank you', and run the same inputs again. Use the free-play step in the 3D to predict which blocks will run.

Key formulas and definitions

Worked examples

1. Name the exception: (a) int('12a') (b) [1,2][5] (c) {'a':1}['b'] (d) 7/0 (e) print(total) with no total

(a) ValueError (b) IndexError (c) KeyError (d) ZeroDivisionError (e) NameError.

2. Find the output when n = 0: try: print(10/n) except ZeroDivisionError: print('A') else: print('B') finally: print('C')

10/0 raises ZeroDivisionError โ†’ except prints A. else is skipped (there was an error). finally prints C. Output: A C.

3. Same code with n = 5. Output?

10/5 = 2.0 is printed. No error, so else prints B. finally prints C. Output: 2.0 B C.

4. Write code that keeps asking until the user types a valid integer.

while True: try: n = int(input('Enter an integer: ')) break except ValueError: print('Not an integer, try again') print('You typed', n)

5. What is printed? try: L = [1, 2] print(L[3]) print('X') except IndexError: print('Y')

L[3] raises IndexError, so print('X') is skipped. except prints Y. Output: Y.

6. Write a function that raises ValueError if marks are not between 0 and 100, and call it safely.

def check(m): if not 0 <= m <= 100: raise ValueError('Marks out of range') return m try: check(120) except ValueError as e: print('Error:', e) # Output: Error: Marks out of range

Common mistakes

Practice quiz

1. Which block always runs?
2. int('xyz') raises:
3. When does the else block run?
4. Which keyword throws an exception on purpose?
5. A missing colon after if gives a:

Practice: answer these yourself

Type or choose your answer, then press Check. Use a hint if you are stuck; the full solution appears after you answer.

Frequently asked questions

What is exception handling in Python?

Catching errors that happen while a program runs, using try and except, so the program can show a message and keep going instead of crashing.

What is the use of finally in Python?

Code in finally runs every time, whether or not an exception happened. It is used for clean-up like closing files.

What is the difference between a syntax error and an exception?

A syntax error breaks the writing rules and is found before running. An exception is an error that occurs during running.

Where this is taught

CBSE (India)Class 12Computational Thinking and Programming - 2

Learn first

Learn next

Related lessons

All Computer Science lessons