Error Handling in Python - 10
1. Error Handling in Python
Definition
Error handling is the process of detecting and managing errors that occur during the execution of a program so that the program does not terminate unexpectedly.
Python provides exception handling using the try and except statements to handle run-time errors and continue the execution of the program.
Benefits of Error Handling
- Prevents the program from crashing.
- Makes programs more reliable and user-friendly.
- Helps identify and fix errors easily.
- Allows the program to continue execution after handling an error.
2. Error
Definition
An error is a mistake in a program that causes it to produce incorrect results or stop executing.
Errors may occur while writing the program or while it is running.
3. Types of Errors
Python errors are mainly classified into three types:
a) Syntax ErrorDefinition
A syntax error occurs when the rules (syntax) of the Python language are violated. These errors are detected before the program begins execution.
Causes
- Missing colon (:)
- Missing brackets or quotation marks
- Incorrect indentation
- Misspelled keywords
Example
if 5 > 3
print("Hello")
Output
SyntaxError: expected ':'
Explanation
The colon (:) after the if statement is missing.
b) Semantic (Logical) ErrorDefinition
A semantic (logical) error occurs when the program runs successfully but produces an incorrect result because of a mistake in the program logic.
These errors are not detected by Python.
Example
length = 8
breadth = 5
area = 2 * (length + breadth)
print("Area =", area)
Output
Area = 26
Explanation
The formula used is for the perimeter, not the area. The correct formula should be:
area = length * breadthc) Run-time Error
Definition
A run-time error occurs while the program is executing. These errors stop the execution of the program if they are not handled.
Run-time errors are also called exceptions.
Common Causes
- Division by zero
- Invalid user input
- Accessing a file that does not exist
- Accessing an invalid list index
Example
num = 10 print(num / 0)
Output
ZeroDivisionError: division by zero
4. Exception
Definition
An exception is an error that occurs during the execution of a program and interrupts its normal flow.
Python raises exceptions whenever a run-time error occurs.
Examples of Exceptions
- ZeroDivisionError
- ValueError
- NameError
- IndexError
- TypeError
- FileNotFoundError
5. How to Handle Exceptions in Python
Python handles exceptions using the try-except mechanism.
The statements that may produce an error are placed inside the try block. If an exception occurs, Python immediately transfers control to the except block, preventing the program from crashing.
6. Exception Handling Statements
Python provides four important keywords for exception handling:
- try
- except
- else
- finally
Description
The try block contains the code that may produce an exception.
If no exception occurs, the program continues normally. If an exception occurs, Python skips the remaining statements in the try block and executes the matching except block.
Example
try:
num = int(input("Enter a number: "))
print(10 / num)
except:
print("An error occurred.")
B. except Block
Description
The except block is used to handle exceptions that occur inside the try block.
It prevents the program from terminating unexpectedly.
Example
try:
num = 10 / 0
except:
print("Division by zero is not allowed.")
Output
Division by zero is not allowed.C. else Block
Description
The else block executes only if no exception occurs in the try block.
It is used to write code that should run only when the program executes successfully.
Example
try:
num = int(input("Enter a number: "))
except:
print("Invalid input.")
else:
print("You entered:", num)
Sample Output
Enter a number: 25 You entered: 25
Explanation
Since no exception occurred, the else block was executed.
D. finally BlockDescription
The finally block is always executed, whether an exception occurs or not.
It is commonly used to release resources, such as closing files or displaying a completion message.
Example
try:
num = 10 / 2
except:
print("An error occurred.")
finally:
print("Program execution completed.")
Output
Program execution completed.
Complete Example Using try, except, else, and finally
Program
try:
num = int(input("Enter a number: "))
result = 100 / num
except ZeroDivisionError:
print("Cannot divide by zero.")
except ValueError:
print("Please enter a valid number.")
else:
print("Result =", result)
finally:
print("Program ended.")
Sample Output 1
Enter a number: 25 Result = 4.0 Program ended.
Sample Output 2
Enter a number: 0 Cannot divide by zero. Program ended.
Sample Output 3
Enter a number: abc Please enter a valid number. Program ended.
Book Exercise(Pg-228)
#14 To divide two numbers given by the user and handles the division by zero error
try:
a=int(input("Enter numerator:"))
b=int(input("Enter denominator:"))
print(a/b)
except ZeroDivisionError:
print("Cannot divide by zero.")
finally:
print("The program was successfully executed.")
#15 Create a list of numbers and try to access an index that doesn't exist. Handle index error.
try:
a=[1,2,3]
for i in range(5):
print(a[i])
except IndexError:
print("List items do not exist after this.")
finally:
print("The program was successfully executed.")
Error Handling Practice Questions
- Ask the user for their age and if their input is in words, pass a friendly message.
- Take input of 2 numbers from the user and use them for division. Catch any division errors or bad inputs possible.
- Create a fixed list of colors and pick out all the colors using the index input by the user. Handle out-of-bounds accessing requests.