9. Exception Handling in Python

Exception handling is used to handle runtime errors gracefully without stopping the program.

It helps:

  • Prevent program crashes
  • Handle unexpected situations
  • Improve program reliability

Types of Errors in Python

Python errors are mainly of two types:

  1. Syntax Errors
  2. Exceptions (Runtime Errors)

1. Syntax Errors

Occurs when Python rules are violated.

Example

if 5 > 2
print("Hello")

Output:

SyntaxError

Missing colon (:).


2. Exceptions (Runtime Errors)

Occurs during program execution.


Common Exception Types

ExceptionDescription
ZeroDivisionErrorDivision by zero
NameErrorVariable not defined
TypeErrorWrong data type
ValueErrorInvalid value
IndexErrorInvalid list index
KeyErrorInvalid dictionary key
FileNotFoundErrorFile does not exist

Example: ZeroDivisionError

x = 10 / 0

try and except

Used to handle exceptions.


Syntax

try:
# risky code
except:
# handling code

Example

try:
num = 10 / 0
except:
print("Error occurred")

Output:

Error occurred

Handling Specific Exceptions

try:
number = int(input("Enter number: "))
result = 10 / number

except ZeroDivisionError:
print("Cannot divide by zero")

except ValueError:
print("Invalid input")

Multiple Exceptions Together

try:
x = int("abc")

except (ValueError, TypeError):
print("Error handled")

else Block

The else block executes if no exception occurs.


Syntax

try:
# code
except:
# error handling
else:
# runs if no error

Example

try:
num = 10 / 2

except ZeroDivisionError:
print("Division error")

else:
print("Result:", num)

Output:

Result: 5.0

finally Block

The finally block always executes whether exception occurs or not.

Used for:

  • Closing files
  • Releasing resources
  • Cleanup operations

Syntax

try:
# code
except:
# handling
finally:
# always executes

Example

try:
file = open("data.txt", "r")

except FileNotFoundError:
print("File not found")

finally:
print("Execution completed")

Complete Example

try:
num = int(input("Enter number: "))
result = 100 / num

except ZeroDivisionError:
print("Cannot divide by zero")

except ValueError:
print("Invalid input")

else:
print("Result:", result)

finally:
print("Program finished")

Raising Exceptions

Use raise keyword to create exceptions manually.


Syntax

raise ExceptionType("message")

Example

age = -5

if age < 0:
raise ValueError("Age cannot be negative")

Example: Custom Validation

password = "123"

if len(password) < 6:
raise Exception("Password too short")

Custom Exceptions

You can create your own exception classes.


Creating Custom Exception

class InvalidAgeError(Exception):
pass

Using Custom Exception

class InvalidAgeError(Exception):
pass

age = -1

try:
if age < 0:
raise InvalidAgeError("Invalid age entered")

except InvalidAgeError as e:
print(e)

Output:

Invalid age entered

Exception Object

Store exception in variable using as.

try:
x = 10 / 0

except ZeroDivisionError as e:
print("Error:", e)

Nested try Blocks

try:
try:
x = 10 / 0
except ZeroDivisionError:
print("Inner exception handled")

except:
print("Outer exception")

User-Defined Function with Exception Handling

def divide(a, b):

try:
return a / b

except ZeroDivisionError:
return "Cannot divide by zero"

print(divide(10, 0))

Best Practices

✅ Handle specific exceptions
✅ Use finally for cleanup
✅ Avoid empty except blocks
✅ Use meaningful error messages
✅ Use custom exceptions for large projects


Practical Example

ATM Withdrawal System

balance = 5000

try:
amount = int(input("Enter withdrawal amount: "))

if amount > balance:
raise Exception("Insufficient balance")

balance -= amount

print("Remaining Balance:", balance)

except ValueError:
print("Please enter valid amount")

except Exception as e:
print(e)

finally:
print("Transaction completed")