Understanding Exception Handling in Python

O

Ohidur Rahman Bappy

MAR 22, 2025

Exception Handling in Python

The cause of an exception is often external to the program itself, such as incorrect input or malfunctioning I/O devices. If an exception occurs, it can cause abrupt termination, potentially damaging system resources like files. Proper handling of exceptions is essential to prevent such abrupt terminations.

Python uses try and except keywords to handle exceptions. Both keywords are followed by indented blocks.

Basic Syntax

try:
    # statements that might throw exception
except:
    # executed when error occurs in try block

The try block contains statements that might encounter an exception. If executed successfully, the except block is skipped. However, if an exception does occur, control is transferred to the except block.

Example: General Exception Handling

try:
    a = 5
    b = '0'
    print(a / b)
except:
    print('Some error occurred.')
print('Out of try-except blocks.')

Result:

Some error occurred.
Out of try-except blocks.

Specifying Exception Types

You can specify a type of exception with the except keyword. This allows handling specific exceptions separately.

Example: Specific Exception Handling

try:
    a = 5
    b = '0'
    print(a + b)
except TypeError:
    print('Unsupported operation')
print('Out of try-except blocks')

Result:

Unsupported operation
Out of try-except blocks

Multiple except clauses can be used for different exception types.

Example: Multiple Exceptions

try:
    a = 5
    b = 0
    print(a / b)
except TypeError:
    print('Unsupported operation')
except ZeroDivisionError:
    print('Division by zero not allowed')
print('Out of try-except blocks')

Result:

Division by zero not allowed
Out of try-except blocks

If b is set to '0', a TypeError is processed by the corresponding except block.

else and finally

In Python, you can also use else and finally with try and except clauses.

  • else: executed if the try block is error-free.
  • finally: executed regardless of whether an exception occurred or not.

Syntax

try:
    # statements in try block
except:
    # executed when error in try block
else:
    # executed if try block is error-free
finally:
    # executed irrespective of exception

Example: Using else and finally

try:
    print('try block')
    x = int(input('Enter a number: '))
    y = int(input('Enter another number: '))
    z = x / y
except ZeroDivisionError:
    print('except ZeroDivisionError block')
    print('Division by 0 not accepted')
else:
    print('else block')
    print('Division = ', z)
finally:
    print('finally block')
    x = 0
    y = 0
print('Out of try, except, else and finally blocks.')

Results:

  1. Normal Execution:
try block
Enter a number: 10
Enter another number: 2
else block
Division =  5.0
finally block
Out of try, except, else and finally blocks.
  1. Exception Occurred:
try block
Enter a number: 10
Enter another number: 0
except ZeroDivisionError block
Division by 0 not accepted
finally block
Out of try, except, else and finally blocks.
  1. Unhandled Exception:
try block
Enter a number: 10
Enter another number: xyz
finally block
Traceback (most recent call last):
  ...
ValueError: invalid literal for int() with base 10: 'xyz'

The finally block is ideal for cleanup, such as closing files.

Raising Exceptions

Python uses the raise keyword to explicitly generate exceptions. Built-in or custom exceptions can be raised.

Example: Raising Exceptions

try:
    x = int(input('Enter a number up to 100: '))
    if x > 100:
        raise ValueError(x)
except ValueError:
    print(x, 'is out of allowed range')
else:
    print(x, 'is within the allowed range')

Result:

Enter a number up to 100: 200
200 is out of allowed range
Enter a number up to 100: 50
50 is within the allowed range