Page 460 - ComputerScience_Class_11
P. 460
Handling Runtime Errors
To prevent runtime errors from crashing your program, Python provides a way to catch and handle them. This is done
using the try...except block.
This is the process of how it works:
• The code that might cause an error is placed inside the try block.
• If no error occurs, the except block is skipped.
• If an error occurs in the try block, the rest of the try block is immediately skipped and the code inside the except
block is executed. This allows the program to recover and continue running.
Program 5: Handling user input errors with try...except.
Program 5.py
File Edit Format Run Options Window Help
try:
age = int(input("Enter your age: "))
print("Next year you will be", age + 1)
except ValueError:
print("Invalid input. Please enter an integer.")
Output
Scenario A (Good Input):
Enter your age: 25
Next year you will be 26
Scenario B (Bad Input):
Enter your age: Twenty Five
Invalid input. Please enter an integer.
In scenario B, instead of crashing with a ValueError, the program catches the error, prints a helpful message and
continues to the final print() statement. You can even handle multiple potential errors by using multiple except blocks.
Program 6: To perform division of two numbers with exception handling for invalid input and division by zero.
Program 6.py
File Edit Format Run Options Window Help
try:
num1 = int(input("Enter numerator: "))
num2 = int(input("Enter denominator: "))
result = num1 / num2
print("Result:", result) Output 1
except ValueError:
Enter numerator: 5
print("Please enter only integers.")
except ZeroDivisionError: Enter denominator: 10
print("You cannot divide by zero.") Result: 0.5
Output 2
Enter numerator: 15
Enter denominator: 0
You cannot divide by zero.
458 Touchpad Computer Science (Ver. 3.0)-XI

