You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
This lesson covers exception handling — the mechanism by which programs detect, report, and recover from runtime errors gracefully. Exception handling is essential for building robust software that does not crash unexpectedly when something goes wrong.
An exception is an event that occurs during program execution that disrupts the normal flow of instructions. Exceptions are typically caused by:
| Cause | Example |
|---|---|
| Invalid input | A user enters "abc" when a number is expected. |
| Division by zero | Attempting to divide by zero. |
| File not found | Trying to open a file that does not exist. |
| Index out of range | Accessing an array element beyond its bounds. |
| Type errors | Performing an operation on an incompatible data type. |
| Network errors | A connection to a server fails. |
Without exception handling, any of these errors would cause the program to crash with an error message.
Exception handling uses a structured approach with try, except (or catch in other languages), and optionally finally blocks.
TRY
x = INPUT("Enter a number: ")
x = INT(x)
result = 100 / x
OUTPUT "Result: " + STR(result)
EXCEPT ZeroDivisionError
OUTPUT "Error: Cannot divide by zero."
EXCEPT ValueError
OUTPUT "Error: Please enter a valid integer."
FINALLY
OUTPUT "Program complete."
END TRY
try:
x = int(input("Enter a number: "))
result = 100 / x
print(f"Result: {result}")
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
except ValueError:
print("Error: Please enter a valid integer.")
finally:
print("Program complete.")
try block is executed.except block.except blocks are skipped.finally block (if present) always executes, whether or not an exception occurred.| Exception Type | When It Occurs |
|---|---|
ValueError | A function receives an argument of the right type but wrong value (e.g., int("abc")). |
TypeError | An operation is applied to an object of the wrong type (e.g., "hello" + 5). |
ZeroDivisionError | Division or modulo by zero. |
IndexError | An index is outside the range of a list or array. |
KeyError | A dictionary key is not found. |
FileNotFoundError | A file or directory is requested but cannot be found. |
IOError | An I/O operation fails (e.g., reading from a corrupted file). |
OverflowError | A numerical result is too large to be represented. |
RecursionError | Maximum recursion depth exceeded. |
You can handle different exception types with separate except blocks, allowing tailored responses to different errors.
def safe_divide(a, b):
try:
result = a / b
return result
except ZeroDivisionError:
print("Cannot divide by zero")
return None
except TypeError:
print("Both arguments must be numbers")
return None
try:
# risky code
pass
except Exception as e:
print(f"An error occurred: {e}")
Exam Tip: Catching all exceptions with a bare
exceptorexcept Exceptionis generally considered bad practice because it can mask bugs. Always catch specific exceptions where possible. However, you should know that it can be used as a "safety net" in production code.
finally BlockSubscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.