Error handling is one of the very important features of any programming language. In Python Programming we have the try-except block to catch and handle exceptions in a graceful way and print the error message in a user-friendly way.
Let's take a look at try-except with an example.
1. dividend = int(input("Enter the dividend: "))
2. divisor = int(input("Enter the divisor: "))
3.
4. try:
5. result = dividend / divisor
6. print(f"Result: {result}")
7. except ZeroDivisionError:
8. print("Error: Division by zero is not allowed")
In the above example, we take the dividend and the divisor as user inputs.
Next we have the try clause which contains a block of statements. When we run this program, if no exception occurs then the except block will not be executed.
Let's run this program and enter some inputs that wil not generate any exceptions.
Enter the dividend: 10
Enter the divisor: 2
Result: 5.0
Enter the dividend: 10
Enter the divisor: 5
Result: 2.0
Now let's try to add a divisor as zero and see what happens.
Enter the dividend: 10
Enter the divisor: 0
Error: Division by zero is not allowed
As you can see, there was an error that occured at line numer 6 and hence the rest of the clause is skipped (line 6 in our case). The control went straignt to the except caluse and it was executed.
Let's try to enter an invalid value as user input and see what happens.
Enter the dividend: a
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-13-de305410bf5d> in <cell line: 1>()
----> 1 dividend = int(input("Enter the dividend: "))
2 divisor = int(input("Enter the divisor: "))
3
4 try:
5 result = dividend / divisor
ValueError: invalid literal for int() with base 10: 'a'

Oops! We get a Traceback printed out, this is because we did not warp the first two lines under try-except thus there was no exception handling for them and no custom message, as ValueError was not handled.
Let's fix this:
try:
dividend = int(input("Enter the dividend: "))
divisor = int(input("Enter the divisor: "))
try:
result = dividend / divisor
print(f"Result: {result}")
except ZeroDivisionError:
print("Error: Division by zero is not allowed")
except ValueError:
print("Invalid input. Please enter valid integers.")
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!