(Grade X)Chapter 4- Programming in Python- Part 5: Error Handling
1. Introduction: What is an Error?
An
error is a mistake or unexpected problem in a program that causes it to stop or
work incorrectly.
When
Python finds an error, it stops the program and shows a traceback. The
traceback tells the line number and type of error, helping the programmer find
and fix the problem.
2. Types of Errors
Errors
in Python are broadly divided into two types: syntax errors and runtime errors
(exceptions).
2.1
Syntax Errors
A
syntax error occurs when Python’s grammar rules are not followed.
Examples:Missing
colon : , Unclosed bracket , Incorrect indentation
Python
finds syntax errors before the program runs during parsing. Therefore, the
program does not execute until the error is fixed.
Program:
|
print("Hello" # missing closing bracket |
Output:
|
File "ex1_syntax_error.py", line 1
print("Hello" ^ SyntaxError: '(' was never closed |
2.2 Runtime Errors (Exceptions)
A
runtime error, also called an exception, occurs while the program is running,
even when the syntax is correct.
Examples:
Dividing by zero, using a variable that does not exist, or entering text
instead of a number.
It
happens due to an unexpected condition during execution.
Program:
|
a = 10 b = 0 print(a / b) # dividing by zero |
Output:
|
Traceback (most recent call last):
File "ex2_zerodiv.py", line 3, in <module>
print(a / b) ZeroDivisionError: division by zero |
3. Common Types of Exceptions
in Python
Python has several
built-in exception types. Some of the most common ones are listed below.
|
Exception |
Occurs When |
|
ValueError |
A function receives an
argument of the correct type but an invalid value, e.g. int("abc") |
|
ZeroDivisionError |
A number is divided by
zero |
|
TypeError |
An operation is
performed on incompatible data types, e.g. "5" + 5 |
|
NameError |
A variable or name is
used before it is defined |
|
IndexError |
A list/string index is
out of the valid range |
|
KeyError |
A dictionary key that does
not exist is accessed |
|
FileNotFoundError |
A file that does not
exist is opened for reading |
Example: A ValueError in
Action
Program:
|
num = int(input("Enter a number: ")) print("You entered:", num) |
Output:
|
Enter a number: abc Traceback (most recent call last): File
"ex3_valueerror.py", line 1, in <module> num =
int(input("Enter a number: ")) ValueError: invalid literal for int() with base 10: 'abc' |
In the example above, the
user typed the text "abc" instead of a number. Since int() cannot
convert this text into an integer, Python raises a ValueError and the program
stops. This is where error handling becomes useful — instead of letting the
program crash, we can catch this error and respond to it properly.
4. The try-except Block
The try-except block is
used to handle errors so the program does not crash.
· try block: Contains code that may cause an error.
· except block: Contains code that runs when an error occurs.
Example
|
|
|
|
|
|
|
|
|
|
Explanation:
try :Runs the code that may cause an error.
except: Runs if an error occurs.
Example: If the user
enters 0, the program shows "An error
occurred."
5. Handling Multiple
Exceptions
A try block can have more
than one except block to handle different errors separately. Python runs the
first matching except block.
Example:
try:
num1 = int(input("Enter numerator:
"))
num2 = int(input("Enter denominator:
"))
result = num1 / num2
print("Result:", result)
except ValueError:
print("Enter valid integers.")
except ZeroDivisionError:
print("Denominator cannot be
zero.")
Examples of errors:
Entering abc → ValueError
Entering 0 as denominator
→ ZeroDivisionError
6. The else Clause
An optional else block can
be added after all the except blocks. The code inside else runs only if the try
block completes successfully, that is, only if no exception occurred.
Program:
|
try: num =
int(input("Enter a number: ")) except ValueError: print("Error:
Invalid input, not a number.") else: print("You
entered a valid number:", num) |
Output:
|
Enter a number: 25 You entered a valid number: 25 |
7. The finally Clause
The finally block is
optional and, if present, always executes — whether an exception occurred or
not, and even if the exception was not handled. It is commonly used for
clean-up actions such as closing a file or displaying a closing message.
Program:
|
try: num =
int(input("Enter a number: ")) print("Number
entered:", num) except ValueError: print("Error:
Please enter a valid number.") finally: print("Program
execution completed.") |
Output:
|
Run 1 (valid input): Enter a number: 42 Number entered: 42 Program execution completed. Run 2 (invalid input): Enter a number: hi Error: Please enter a valid number. Program execution completed. |
|
Note: Order of execution: try
→ (except, only if an error occurred) → (else, only if no error occurred) →
finally (always). |
examples:
1.
ValueError
Question:
Write a Python program to input a number from the user and handle the ValueError
exception if the user enters an invalid value.
try:
n = int(input("Enter a number:
"))
print("Number =", n)
except
ValueError:
print("Invalid input! Please enter a
number.")
Output:
Enter
a number: abc
Invalid
input! Please enter a number.
2.
ZeroDivisionError
Question:
Write a Python program to input two numbers and divide the first number by the
second number. Handle the ZeroDivisionError if the denominator is zero.
try:
numerator = int(input("Enter
numerator: "))
denominator = int(input("Enter
denominator: "))
result = numerator / denominator
print("Result =", result)
except
ZeroDivisionError:
print("Cannot divide by zero.")
Output:
Enter
numerator: 20
Enter
denominator: 0
Cannot
divide by zero.
3.
TypeError
Question:Write
a Python program to add an integer and a string and handle the TypeError
exception.
try:
a = 10
b = "5"
result = a + b
print("Result =", result)
except
TypeError:
print("Cannot add integer and
string.")
Output:
Cannot
add integer and string.
4.
NameError
Question:Write
a Python program to display an undefined variable and handle the NameError
exception.
try:
print(number)
except
NameError:
print("Variable is not defined.")
Output:
Variable
is not defined.
5.
IndexError
Question:Write
a Python program to create a list of numbers and try to access an index that
does not exist. Handle the IndexError using try-except.
try:
numbers = [10, 20, 30, 40, 50]
print(numbers[7])
except
IndexError:
print("Index does not exist.")
Output:
Index
does not exist.
6.
KeyError
Question:
Write a Python program to create a dictionary and try to access a key that does
not exist. Handle the KeyError using try-except.
try:
student = {
"name": "Ram",
"age": 15
}
print(student["address"])
except
KeyError:
print("Key does not exist.")
Output:
Key
does not exist.
7.
FileNotFoundError
Question:
Write a Python program to open a file named student.txt for reading and handle
the FileNotFoundError if the file does not exist.
try:
f = open("student.txt",
"r")
print(f.read())
f.close()
except
FileNotFoundError:
print("File not found.")
Output:
File
not found.
8. The try-except Block
Question:
Write
a Python program to input two numbers and divide them using a try-except block
to handle division by zero.
try:
a = int(input("Enter first number:
"))
b = int(input("Enter second number:
"))
result = a / b
print("Result =", result)
except
ZeroDivisionError:
print("Cannot divide by zero.")
Output:
Enter
first number: 25
Enter
second number: 5
Result
= 5.0
9. Handling Multiple Exceptions
Question:
Write a Python program to input two numbers and divide them. Handle both ValueError
and ZeroDivisionError exceptions.
try:
a = int(input("Enter numerator:
"))
b = int(input("Enter denominator:
"))
result = a / b
print("Result =", result)
except
ValueError:
print("Please enter numbers
only.")
except
ZeroDivisionError:
print("Cannot divide by zero.")
Output
1:
Enter
numerator: abc
Please
enter numbers only.
Output
2:
Enter
numerator: 20
Enter
denominator: 0
Cannot
divide by zero.
10. The else Clause
Question:Write
a Python program to divide two numbers using try-except-else. Display the
result in the else block if no exception occurs.
Program:
try:
a = int(input("Enter numerator:
"))
b = int(input("Enter denominator:
"))
result = a / b
except
ZeroDivisionError:
print("Cannot divide by zero.")
else:
print("Result =", result)
Output:
Enter
numerator: 20
Enter
denominator: 4
Result
= 5.0
Remember:
else runs only when there is no error.
11. The finally Clause
Question:
Write a Python program to divide two numbers using try-except-finally. Display
a message from the finally block after program execution.
try:
a = int(input("Enter numerator: "))
b = int(input("Enter denominator:
"))
result = a / b
print("Result =", result)
except
ZeroDivisionError:
print("Cannot divide by zero.")
finally:
print("Program execution
completed.")
Output:
Enter
numerator: 10
Enter
denominator: 0
Cannot
divide by zero.
Program
execution completed.
Remember:
finally executes whether an error occurs or not.