Definition:
If you write multiple except blocks for a single try block, the developer can easily understand which type of error has occurred and handle it properly.
It is called multiple except blocks.
Now you will clearly understand the code logic with the help of the flowchart.
Multiple Except Blocks Flowchart:
First step: → You write the program
|
↓
Second step: → try block will execute
|
↓
Third step: → Check which type of error has occurred
|
┌───────────────┬───────────────┬───────────────┐
↓ ↓ ↓
If ValueError occurs If any other error If no error occurs
| | |
↓ ↓ ↓
Print: Value error Print: Any other Print result
invalid input error
| | |
↓ ↓ ↓
End the program
Syntax:
try:
# risky code
except ValueError:
# message for value error
except TypeError:
# message for type error
except Exception:
# general error message
Example:
try:
num = int(input("Enter a number: "))
result = 4 + num
print("Result =", result)
except ValueError:
print("Value error: invalid input")
except Exception:
print("Any other error")
Output:
Exercise
Write a Python program that takes a number as input and handles ValueError using multiple except blocks.
