Tutorials Home   >   Core Programming Concepts   >   Runtime Exceptions

Runtime Exceptions

Introduction to Runtime Exceptions

In programming, errors can occur while a program is running. These errors are called exceptions.

Runtime exceptions are errors that occur during the execution of a program. They do not occur during compilation.

Unlike syntax errors (which prevent the program from running), runtime exceptions appear while the program is executing, and if not handled, they can cause the program to crash.


2. What Is a Runtime Exception?

Definition:

A runtime exception is an error that happens while a program is running, usually due to invalid operations or unexpected situations.

These errors are usually logical errors or unforeseen conditions in the program.

Real-Life Example:

  • Dividing a number by zero

  • Accessing a list element that doesn’t exist

  • Opening a file that doesn’t exist


3. Common Causes of Runtime Exceptions

  1. Division by zero

  2. Null reference or None object

  3. Invalid type operations

  4. Array or list index out of range

  5. File not found

  6. Invalid user input

  7. Memory overflow


4. Examples of Runtime Exceptions in Python

Example 1: Division by Zero

a = 10
b = 0
print(a / b) # ZeroDivisionError

Example 2: Accessing Invalid List Index

numbers = [1, 2, 3]
print(numbers[5]) # IndexError

Example 3: Using an Undefined Variable

print(x) # NameError

Example 4: Invalid Type Operation

num = 10
text = "Hello"
print(num + text) # TypeError

5. Runtime Exceptions vs Compile-Time Errors

Feature Compile-Time Error Runtime Exception
Occurrence During compilation During program execution
Examples Syntax errors, missing semicolon Division by zero, index out of range
Detection Compiler detects Program runs but crashes if not handled
Prevention Correct syntax Use exception handling
Handling Not possible Can handle with try-except blocks

6. Handling Runtime Exceptions

Most programming languages provide exception handling mechanisms to manage runtime exceptions.

In Python: try-except

try:
a = 10
b = 0
print(a / b)
except ZeroDivisionError:
print("Cannot divide by zero!")

Output:

Cannot divide by zero!

Explanation:

  • The try block contains code that may raise an exception

  • The except block catches and handles the exception

  • Program continues running without crashing


7. Multiple Exceptions Handling

You can handle different types of exceptions in one try block.

numbers = [1, 2, 3]
try:
x = numbers[5]
y = 10 / 0
except IndexError:
print("Invalid index!")
except ZeroDivisionError:
print("Cannot divide by zero!")

Output:

Invalid index!

Explanation:

  • Python executes the except block that matches the exception type


8. Catching All Exceptions

You can catch any runtime exception using a general except block:

try:
x = int(input("Enter a number: "))
print(10 / x)
except Exception as e:
print("An error occurred:", e)
  • Exception is the base class for all exceptions

  • Variable e holds the exception message


9. Raising Exceptions Manually

You can raise runtime exceptions intentionally using the raise keyword.

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

Output:

ValueError: Age cannot be negative

Explanation:

  • raise allows the programmer to signal errors manually

  • Helps in input validation and enforcing rules


10. Advantages of Exception Handling

  1. Prevents program crashes

  2. Improves reliability

  3. Provides meaningful error messages

  4. Separates normal logic from error handling

  5. Allows recovery from errors


11. Common Runtime Exceptions in Python

Exception Cause
ZeroDivisionError Dividing by zero
IndexError Accessing invalid index in list/tuple
KeyError Accessing invalid key in dictionary
TypeError Performing invalid operation between types
ValueError Invalid value for an operation
NameError Using undefined variable
FileNotFoundError Opening a file that doesn’t exist

12. Best Practices for Handling Runtime Exceptions

  1. Always handle expected exceptions using try-except

  2. Avoid empty except blocks – specify the exception type

  3. Use finally block to execute cleanup code

  4. Validate user input to prevent exceptions

  5. Use custom exceptions for application-specific errors

Example with finally:

try:
file = open("data.txt")
data = file.read()
except FileNotFoundError:
print("File not found!")
finally:
print("This block always executes")

13. Conclusion

Runtime exceptions are errors that occur during program execution and can crash a program if not handled.

  • Understanding runtime exceptions helps learners write more reliable and robust programs.

  • Using exception handling (try-except-finally) allows programs to recover from errors gracefully.

  • Runtime exceptions are a key concept in modern programming, especially when dealing with user input, files, and dynamic operations.