Xii Cs Worksheet-exceptions
Xii Cs Worksheet-exceptions
Example
def check_age(age):
if age < 18:
raise ValueError("Age must be 18 or above.")
else:
print("You are allowed to proceed.")
try:
user_age = int(input("Enter your age: "))
check_age(user_age)
except ValueError as e:
print(f"Error: {e}")
Expected Output: The average of the numbers [10, 20, 30, 40, 50] should be 30.
Actual Output: The program will output The average is: 29.0.
RuntimeError A runtime error in a program is one that occurs after the program has been successfully
compiled.
The Python interpreter will run a program if it is syntactically correct (free of syntax errors).
However, if the program encounters a runtime error - a problem that was not detected when
the program was parsed and is only revealed when a specific line is executed - it may exit
unexpectedly during execution. When a program crashes due to a runtime error, we say it has
crashed
Some examples of Python Runtime errors :
division by zero
performing an operation on incompatible types
using an identifier that has not been defined
accessing a list element, dictionary value, or object attribute which doesn’t exist
trying to access a file that doesn’t exist