Python: try-except Print Error Message Example

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: "))
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: "))
      4 try:
      5     result = dividend / divisor

ValueError: invalid literal for int() with base 10: 'a'
Python try-except print error message example

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:

    dividend = int(input("Enter the dividend: "))
    divisor = int(input("Enter the divisor: "))
        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.")

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail:

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap