ERROR HANDLING IN PYTHON
What are errors? These "errors" are feedback that tells you what needs to be changed, not failures. Programming functions in precisely the same manner. Fundamentally, an error is Python's way of expressing, "I don't know how to proceed with what you have asked me to do."
The Two Main Error Families
Syntax Errors: The Grammar Mistakes
Python requires specific structures and once they are not followed it throws out error. These mistakes happen at the parsing stage, prior to your code executing.
Exceptions: The Runtime Surprises
Everything is grammatically fine, yet something unexpected occurs for instance trying to open a file that doesn't exist or dividing by zero.
Basic Error Handling
Python uses Try, Except, Else, Finally to anticipate errors and sort them out instead of allowing your code to crash.
Example: try-except
try:
y = int(input("Enter a number: "))
print(10 / y)
except ZeroDivisionError:
print("You cannot divide by zero.")
except ValueError:
print("Invalid input. Please enter a number.")
If the user inputs zero “0” instead of crashing your code, it will print “You cannot divide by zero". This informs the user of their error. Also if the user enters letters instead of number the except ValueError will be executed.
Example: Catching multiple exceptions
try:
result = 10 / int("0")
except Exceptions:
print("An error occurred.")
This targets the whole error and prints “an error occured", it is not specific.
Example: Else with try-except
try:
num = int(input("Enter a number: "))
except ValueError:
print("Invalid number.")
else:
print("You entered:", num)
Example: Finally block
file = open("media.ppt")
except FileNotFoundError:
print("File not found.")
finally:
print("Execution completed.")
Finally runs whether there is error or not. It is used in cleaning up.
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)