Tutorials Home   >   Core Programming Concepts   >   Exception Handling

Exception Handling

 Introduction to Exceptions

Imagine you are following a recipe to bake a cake. Everything goes smoothly—until you accidentally drop the eggs on the floor. What do you do? You handle the problem, maybe by getting fresh eggs, instead of stopping your cooking entirely.

In programming, similar “unexpected problems” can happen. These problems are called exceptions.

What is an Exception?

An exception is an event that disrupts the normal flow of a program. It is usually caused by errors, such as:

  • Dividing a number by zero.

  • Trying to open a file that doesn’t exist.

  • Accessing a list element that is out of range.

For example, in Python:

print(10 / 0) # This will cause a ZeroDivisionError

Without handling it, the program will stop immediately and show an error message, which is not ideal for user-friendly applications.


Why Handle Exceptions?

  • Prevent program crashes: Users won’t see ugly error messages.

  • Allow recovery: Programs can try an alternative plan if something goes wrong.

  • Debugging: Exception messages help identify issues during development.


Page 2: How Exception Handling Works

Most programming languages provide a structured way to handle exceptions, usually through try, catch (or except), and sometimes finally.

Basic Syntax in Python

try:
num = int(input("Enter a number: "))
print(10 / num)
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("That’s not a valid number!")
finally:
print("Execution completed.")

Explanation:

  1. try block: Code that might cause an exception goes here.

  2. except block: Code that executes if a specific exception occurs.

  3. finally block (optional): Code that always runs, whether there was an exception or not. Useful for closing files or releasing resources.

Output example:

Enter a number: 0
Cannot divide by zero!
Execution completed.

Even though there was an error, the program did not crash.


Types of Exceptions

Some common built-in exceptions in Python:

Exception Name Cause
ZeroDivisionError Dividing a number by zero
ValueError Invalid input type (e.g., string instead of number)
IndexError Accessing a list or array out of bounds
FileNotFoundError Trying to open a file that doesn’t exist
TypeError Performing an operation on incompatible types

Tip: You can also create custom exceptions for your specific program errors.


Page 3: Advanced Exception Handling Concepts

Multiple Exceptions in One Block

You can handle multiple exceptions in one except:

try:
nums = [1, 2, 3]
print(nums[5])
except (IndexError, ZeroDivisionError) as e:
print("An error occurred:", e)
  • Using as e allows you to capture the error message for logging or debugging.


Raising Exceptions

Sometimes you want to intentionally trigger an exception if something unexpected happens:

age = int(input("Enter your age: "))
if age < 0:
raise ValueError("Age cannot be negative!")
  • raise allows you to signal that something is wrong, which can be caught later.


Best Practices

  1. Catch specific exceptions instead of a general one.

    • ✅ except ZeroDivisionError:

    • ❌ except: (too broad)

  2. Clean up resources using finally or with (context managers in Python).

  3. Don’t ignore exceptions silently — always log or handle them meaningfully.


Page 4: Real-Life Analogy and Examples

Analogy: Traffic Control

Think of a program as a car driving on a road:

  • A normal road = normal code execution.

  • Unexpected potholes or accidents = exceptions.

  • Traffic signals and safety barriers = exception handling that ensures the car reaches its destination safely.


Example: Reading a File Safely

try:
file = open("data.txt", "r")
content = file.read()
print(content)
except FileNotFoundError:
print("File does not exist!")
finally:
file.close()
print("File closed.")
  • Even if the file is missing, the program won’t crash.

  • The finally block ensures the file is always closed.


Summary

  1. Exceptions are errors that disrupt normal program flow.

  2. Exception handling ensures your program runs smoothly even when errors occur.

  3. Key tools:

    • try → code that may fail

    • except → handle the error

    • finally → run cleanup code

    • raise → trigger custom errors

  4. Following best practices improves reliability, debugging, and user experience.