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!
- Python: Convert Date to DateTime
- How to sort a List using Lambda in Python
- Python matplotlib segmentation fault: 11 macOS Big Sur
- What is Terminal Velocity and its Formula? How to calculate it programmatically?
- How to install Python 3.11 on Mac
- How to flatten a nested list in Python
- Python: Pandas Merge DataFrames on Index Example
- How to Run all Cells at Once Jupyter Notebook
- Python - Convert float to String
- How to add borders to tkinter label text
- How to Exit a Loop in Python Code
- [Python] Fix: ValueError: All arrays must be of the same length
- Sorting an array using Bubble Sort in Python Programming
- How to Unzip a file using Python
- Python: Merge DataFrames Pandas Outer Join Example
- Change label (text) color in tkinter
- Convert Float to String in Python
- Fix: fatal error: No such file or directory compilation terminated
- Python: Access index/counter of a for loop iteration
- Import Other Python Files Examples
- How to install Anaconda on Mac (M1/M2 Mac)
- Python Regular Expression to Find All Matches in List
- How to Read a binary File with Python
- How to disable warnings while Python file execution
- Know current Python Version
- 24: Append One String to Another in Python Program - Python-Programs
- Vertically Center Text in a DIV Element - CSS
- Fix: Error: error:0308010C:digital envelope routines::unsupported NodeJs/Vue/React - JavaScript
- SQLite Error: unknown command or invalid arguments: open. Enter .help for help - Android
- Get HTTP Request Response Headers Safari Browser - MacOS
- iOS 14 Airpods Connected message everytime when the iPhone is unlocked - Apple
- Ubuntu zsh: command not found: nano - zsh
- Program 12: Calculate Area and Circumference of Circle - 1000+ Python Programs - Python-Programs