⚡0 XP🔥0

Exception Handling (try, except, finally)

Lesson 24 of 33 ⏱ 5 min read ✎ 3 exercises ❓ 5-question quiz ▶ Runs Python

Handle runtime errors gracefully with try/except/else/finally, catch specific exceptions, raise your own errors and create custom exception classes.

Errors happen#

Even correct programs face problems at run time: the user types text instead of a number, a file is missing, the internet is down, someone divides by zero. Without handling, the program crashes with a traceback.

▶ Try it YourselfPython
Ctrl + Enter to run

There are two kinds of errors:

Syntax errors Exceptions (runtime errors)
Code breaks Python's grammar Code is valid, but something goes wrong while running
Found before the program runs Happen during execution
e.g. missing : or bracket e.g. dividing by zero, missing file
Must be fixed in the code Can be handled with try/except

Reading a traceback#

Traceback (most recent call last):
  File "main.py", line 2, in <module>
    x = int("ten")
ValueError: invalid literal for int() with base 10: 'ten'

Read it from the bottom: the last line gives the exception type (ValueError) and a message. The lines above show where it happened (file and line number).

Common built-in exceptions#

Exception When it happens Example
ZeroDivisionError dividing by zero 10 / 0
ValueError right type, bad value int("abc")
TypeError wrong type for an operation "5" + 5
NameError variable not defined print(undefined_var)
IndexError list index out of range [1, 2][5]
KeyError dict key not found {"a": 1}["b"]
AttributeError object has no such attribute "abc".push()
FileNotFoundError file doesn't exist open("nofile.txt")
ImportError / ModuleNotFoundError module can't be imported import nonexistent

try and except#

Put risky code in try. If an exception happens, Python jumps to the matching except block instead of crashing:

▶ Try it YourselfPython
Ctrl + Enter to run
हिंदी में समझें

try / except को ऐसे समझें: "यह काम कोशिश करो (try); अगर कोई गड़बड़ हो जाए, तो program बंद करने की बजाय यह करो (except)।"

जैसे ATM - अगर आपने गलत PIN डाला, तो मशीन बंद नहीं हो जाती, बल्कि message दिखाती है "Wrong PIN, try again"। यही exception handling है - error को पकड़ना और समझदारी से संभालना, ताकि program crash न हो।

Catching specific exceptions#

Handle different problems differently:

▶ Try it YourselfPython
Ctrl + Enter to run

Catch several types in one block with a tuple, and get the error message with as:

▶ Try it YourselfPython
Ctrl + Enter to run
Common Mistake

Avoid a bare except: or except Exception: that catches everything - it hides real bugs (even typos in variable names). Catch the specific exceptions you expect.

else and finally#

try:
    # risky code
except SomeError:
    # runs if that error happened
else:
    # runs only if NO error happened
finally:
    # ALWAYS runs - error or not
▶ Try it YourselfPython
Ctrl + Enter to run

finally is used for clean-up: closing files, database connections, network sockets - things that must happen even if something fails.

Raising exceptions#

Use raise to signal an error in your own code - for example, when a function receives invalid input:

▶ Try it YourselfPython
Ctrl + Enter to run

Custom exceptions#

For bigger programs, create your own exception classes (you'll learn classes in the OOP chapter):

▶ Try it YourselfPython
Ctrl + Enter to run

A robust input pattern#

▶ Try it YourselfPython
Ctrl + Enter to run

Summary#

  • Exceptions are runtime errors; read tracebacks from the bottom.
  • try: risky code → except SpecificError: handle it.
  • else: runs when no error occurred; finally: always runs (clean-up).
  • Catch specific exceptions; avoid bare except:.
  • raise ValueError("message") signals errors; subclass Exception for custom errors.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Safe division

Write safe_divide(a, b) that returns a / b, but returns the string "Cannot divide by zero" if b is 0. Use try/except (not an if-check).

2

Read a valid number

Lines of input are given. Keep reading until you get a valid integer, printing Invalid: <text> for each bad line. Then print Got <number>.

Test input:
abc
12.5
seven
42
Expected output:
Invalid: abc
Invalid: 12.5
Invalid: seven
Got 42
3

Validate age

Write set_age(age) that raises ValueError("Age must be between 0 and 120") if age is outside 0-120, otherwise returns the age.

Quick Quiz

Q1.

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

Q2.

Which exception does int("abc") raise?

Q3.

When does the else block of a try statement run?

Q4.

When does the finally block run?

Q5.

How do you raise an error yourself?