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.")
Facing issues? Have Questions? Post them here! I am happy to answer!
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: rakesh@code2care.org
- How to convert int to ASCII in Python
- How to make use of SQLite Module in Python?
- Split a String into Sub-string and Parse in Python
- Python: Pandas Rename Columns with List Example
- How to run Python file from Mac Terminal
- How to Exit a Loop in Python Code
- Python: How to Plot a Histogram using Matplotlib and data as list
- MD5 Hashing in Python
- Jupyter: Safari Cant Connect to the Server localhost:8888/tree
- Fix: AttributeError: str object has no attribute decode. Did you mean: encode?[Python]
- How to Read a binary File with Python
- How to add two float numbers in Python
- Python: How to install YAML Package
- Python: How to Save Image from URL
- What is Markdown in Jupyter Notebook with Examples
- How to change the Python Default version
- 33: Python Program to send an email vid GMail
- How to comment code in Python
- How to Fix AttributeError in Python
- Fix: error: Jupyter command `jupyter-nbconvert` not found [VSCode]
- How to comment out a block of code in Python
- List of All 35 Reserved Keywords in Python Programming Language 3.11
- Import Other Python Files Examples
- Python: How to add Progress Bar in Console with Examples
- 3 Ways to convert bytes to String in Python
- MySQL : Error :1004 SQLSTATE: HY000 (ER_CANT_CREATE_FILE) Can't create file - MySQL
- How to Determine Android Studio Gradle Version - Android-Studio
- How to send SMS on Android Emulator - Android
- Spell check not working in Gmail : Mac OS X - Mac-OS-X
- Convert SQL to CSV in Notepad++ - NotepadPlusPlus
- zsh hello world example - Linux
- How to uninstall Visual Studio Code on macOS - MacOS
- Fix: pip install mysqlclient error: subprocess-exited-with-error - MySQL