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
- Find Difference of two numbers - C-Program
- Microsoft Edge browser error on MAC - This page is having a problem Try coming back to it later - Microsoft
- How to Change the Default Notepad++ Installation Location - NotepadPlusPlus
- macOS: Text to Speech Command - say examples - MacOS
- Program 13: Reverse a String - 1000+ Python Programs - Python-Programs
- How to add Sleep to PowerShell Script - Powershell
- Program 41: Take a year as input and print whether it is a leap year or not [Python] - Python-Programs
- How to Display Current Date and Time in UTC/GMT in Mac Terminal - MacOS