Exception Handling in Python

August 06, 2025   4 Min Read 30

What You’ll Learn in This Blog

  • Why exception handling is important
  • Common runtime errors in Python
  • Using try, except, else, finally blocks
  • Catching specific vs. generic exceptions
  • Raising exceptions manually with raise
  • Creating your own custom exceptions
  • Best practices with real-world examples

Why Do We Need Exception Handling?

In read-world applications, errors will happen — a user might provide wrong input, a file might be missing, or an API might fail.

Instead of crashing the program, Python provides a graceful way to handle errors using exception handling.

Common Runtime Errors (Exceptions)

Here are a few examples:

ErrorReason
ZeroDivisionErrorDividing a number by zero
FileNotFoundErrorTrying to open a non-existing file
TypeErrorWrong data type used in operation
ValueErrorWrong value passed
IndexErrorAccessing out-of-bound index
KeyErrorAccessing a missing dictionary key

Basic Structure of Exception Handling


try:
	# risky code
except SomeError:
	# handle the error
else:
	# runs if no exception
finally:
	# always runs

Example: Try and Except


try:
	num = int(input("Enter a number: "))
	result = 10 / num
	print("Result:", result)
except ZeroDivisionError:
	print("You cannot divide by zero.")
except ValueError:
	print("Please ener a valid number.")

Using else and finally

  • else runs only if no error occurs
  • finally always runs (cleanup code, closing files, etc.)

try:
	f = open("data.txt", "r')
	content = f.read()
except FileNotFoundError:
	print("File not found!")
else:
	print("File read successfully.")
finally:
	f.close()
	print("File Closed.")

Catching Multiple Exceptions Together


try:
	value = int("abc")
	print(10 / 0)
except (ValueError, ZeroDivisionError) as e:
	print("Caught an error:", e)

Raising Exceptions Manually with raise

You can raise exceptions if needed:


age = -5
if age < 0:
	raise ValueError("Age cannot be negative!")

Custom Exceptions in Python

Create your own exceptions by inheriting from Exception:


class InvalidAgeError(Exception):
	pass


age = int(input("Enter age: "))
if age < 0:
	raise InvalidAgeError("Custom: Age can't be negative.")

Best Practices

  • Be specific with exception types (avoid except: alone)
  • Log errors for debugging (use logging module)
  • Clean up using finally
  • Use custom exceptions to make errors meaningful
  • Avoid hiding bugs by catching too broadly

Practice Task

Create a function that:

  • Accepts a list of numbers.
  • Returns the average.
  • Raises and handles;
    • TypeError if input is not a list
    • ZeroDivisionError if list is empty

Summary Table

ConceptKeywordUse Case
Handle errortry/exceptGracefully catch runtime errors
No error blockelseRuns if no exceptions occur
Always runfinallyClean-up actions like closing files
Manual raiseraiseRaise your own exception
Custom errorclassCreate domain-specific error types

Leave a Reply