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
a = 10
b = 0
print(a / b)
print('This line never runs')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
| Exception | Raised when | Example |
|---|---|---|
| ZeroDivisionError | Division or modulus by zero | 10 / 0 |
| ValueError | Right type but wrong value | int('abc') |
| TypeError | Operation on the wrong type | '2' + 2 |
| IndexError | Index out of range | [1, 2][5] |
| KeyError | Dictionary key not found | {'a': 1}['b'] |
| NameError | Name not defined | print(undefined_var) |
| AttributeError | Object has no such attribute/method | (5).append(1) |
| ModuleNotFoundError / ImportError | Module cannot be imported | import mathh |
| FileNotFoundError | File does not exist | open('nofile.txt') |
| EOFError | input()/pickle.load() reaches end of file | reading past the last record |
| OverflowError | Result too large | 2.0 ** 10000 |
| IndentationError | Wrong 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.
try and except
try:
a = 10
b = 0
print(a / b)
except ZeroDivisionError:
print('Cannot divide by zero!')
print('Program continues normally')try, except, else, finally
try:
statements that may raise an exception
except ExceptionName:
handle that exception
else:
runs only if NO exception occurred
finally:
runs ALWAYS (clean-up)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')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.
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)A bare except: or except Exception: catches almost everything — put it last, after specific handlers:
try:
x = [1, 2, 3]
print(x[3])
except Exception as e: # catches almost every error
print('Something went wrong:', e)raise and assert
raise lets your code signal an error. assert condition, message raises AssertionError when the condition is False — handy for checking inputs.
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)Exceptions with files and input
try:
f = open('marks_missing.txt')
print(f.read())
f.close()
except FileNotFoundError:
print('File not found – please check the name')Keep asking until valid input is given:
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)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.
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).
