Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🐍 Unit 1 – Python Revision & Functions  ·  Lesson 04

Exception Handling (try-except)

Errors: syntax errors vs exceptions

Syntax error

  • Code breaks grammar rules of Python
  • Detected before the program runs
  • Example: missing colon, bracket, quote
  • Must be fixed in the code

Exception (run-time error)

  • Code is valid, but something goes wrong while running
  • Example: 10/0, int("abc"), missing file
  • Program crashes if not handled
  • Can be handled with try-except
Two kinds of errors
Python
a = 10
b = 0
print(a / b)
print('This line never runs')
ZeroDivisionError: division by zero

When an exception is raised and not handled, Python stops the program and prints a traceback whose last line names the exception.

Built-in exceptions

ExceptionRaised whenExample
ZeroDivisionErrorDivision or modulus by zero10 / 0
ValueErrorRight type but wrong valueint('abc')
TypeErrorOperation on the wrong type'2' + 2
IndexErrorIndex out of range[1, 2][5]
KeyErrorDictionary key not found{'a': 1}['b']
NameErrorName not definedprint(undefined_var)
AttributeErrorObject has no such attribute/method(5).append(1)
ModuleNotFoundError / ImportErrorModule cannot be importedimport mathh
FileNotFoundErrorFile does not existopen('nofile.txt')
EOFErrorinput()/pickle.load() reaches end of filereading past the last record
OverflowErrorResult too large2.0 ** 10000
IndentationErrorWrong indentation (a syntax error)missing indented block

Why handle exceptions?

Exception handling lets a program respond to problems gracefully instead of crashing — show a friendly message, ask again, use a default, close files safely. The code that might fail goes in try; the code that handles the problem goes in except.

Startrun the try blockexception raised?YesNorun else blockmatching except blockfinally block (always)continue program
How Python executes try-except-else-finally

try and except

Python
try:
    a = 10
    b = 0
    print(a / b)
except ZeroDivisionError:
    print('Cannot divide by zero!')
print('Program continues normally')
Cannot divide by zero! Program continues normally

try, except, else, finally

Syntax
try:
    statements that may raise an exception
except ExceptionName:
    handle that exception
else:
    runs only if NO exception occurred
finally:
    runs ALWAYS (clean-up)
Python
def safe_divide(x, y):
    try:
        result = int(x) / int(y)
    except ZeroDivisionError:
        print('Error: divisor is zero')
    except ValueError:
        print('Error: enter whole numbers only')
    else:
        print('Result =', result)       # runs only if no exception
    finally:
        print('-- finished --')         # always runs

safe_divide('20', '4')
safe_divide('20', '0')
safe_divide('20', 'x')
Result = 5.0 -- finished -- Error: divisor is zero -- finished -- Error: enter whole numbers only -- finished --

Handling several exceptions

Use several except blocks, or one block with a tuple of exception names. as e gives the exception object, whose message can be printed.

Python
data = [10, 20, 30]
for idx in ['1', '5', 'two']:
    try:
        print(data[int(idx)])
    except (IndexError, ValueError) as e:      # one block for many types
        print(type(e).__name__, '->', e)
20 IndexError -> list index out of range ValueError -> invalid literal for int() with base 10: 'two'

A bare except: or except Exception: catches almost everything — put it last, after specific handlers:

Python
try:
    x = [1, 2, 3]
    print(x[3])
except Exception as e:          # catches almost every error
    print('Something went wrong:', e)
Something went wrong: list index out of range

raise and assert

raise lets your code signal an error. assert condition, message raises AssertionError when the condition is False — handy for checking inputs.

Python
def set_marks(m):
    if m < 0 or m > 100:
        raise ValueError('Marks must be between 0 and 100')
    return m

for m in (88, 140):
    try:
        print('Saved', set_marks(m))
    except ValueError as err:
        print('Error:', err)
Saved 88 Error: Marks must be between 0 and 100

Exceptions with files and input

Python
try:
    f = open('marks_missing.txt')
    print(f.read())
    f.close()
except FileNotFoundError:
    print('File not found – please check the name')
File not found – please check the name

Keep asking until valid input is given:

Python
while True:
    try:
        n = int(input('Enter a positive number: '))
        assert n > 0, 'number must be positive'
        break
    except ValueError:
        print('Not a number, try again')
    except AssertionError as e:
        print('Invalid:', e)
print('You entered', n)
Enter a positive number: abc Not a number, try again Enter a positive number: -4 Invalid: number must be positive Enter a positive number: 12 You entered 12

Flow of control

  • No exception in try → else runs → finally runs.
  • Exception in try → rest of try is skipped → first matching except runs → finally runs.
  • Exception with no matching except → finally runs → program stops with the traceback.

Summary & practice

  • Syntax errors are found before running; exceptions happen while running.
  • try–except catches exceptions; else runs if none; finally always runs.
  • Catch specific exceptions first; use raise / assert for your own checks.
✅ Board-style question

What is printed? try: print('A'); x = int('5a'); print('B') except ValueError: print('C') else: print('D') finally: print('E')

Answer: A, C, E (each on a new line).

Frequently Asked Questions

What is the difference between an error and an exception?
A syntax error stops the program before it starts because the code breaks Python’s rules. An exception is an error detected while the program is running (like division by zero); it can be caught and handled with try-except.
When does the else block of try run?
Only when the try block finishes without raising any exception.
Does finally run even if there is no exception?
Yes. finally always runs — whether an exception occurred or not — so it is used for clean-up like closing files.
← Class 12 Computer Science
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

Next topicText Files: open, read, write, seek Your progress: 4 / 26 (15%) · Lesson 5 / 26 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free