Exceptions help us find and handle errors in our programs so they don't crash unexpectedly.
0
0
Common exception types in Python
Introduction
When reading a file that might not exist.
When dividing numbers and the divisor could be zero.
When converting user input to a number that might be invalid.
When accessing a list item that might be out of range.
When working with keys in a dictionary that might not be present.
Syntax
Python
try: # code that might cause an error except ExceptionType: # code to handle the error
Replace ExceptionType with the specific error you want to catch.
You can catch multiple exceptions by listing them in parentheses.
Examples
This catches the error when dividing by zero.
Python
try: x = 1 / 0 except ZeroDivisionError: print("Cannot divide by zero!")
This catches the error when converting a string that is not a number.
Python
try: value = int('abc') except ValueError: print("Invalid number!")
This catches the error when accessing a list index that does not exist.
Python
try: my_list = [1, 2, 3] print(my_list[5]) except IndexError: print("Index is out of range!")
Sample Program
This program asks the user for a number, then divides 10 by that number. It handles errors if the input is not a number or if the number is zero.
Python
try: number = int(input("Enter a number: ")) result = 10 / number print(f"10 divided by {number} is {result}") except ValueError: print("Oops! That is not a valid number.") except ZeroDivisionError: print("Oops! Cannot divide by zero.")
OutputSuccess
Important Notes
Always catch specific exceptions instead of a general Exception to avoid hiding bugs.
You can use multiple except blocks to handle different errors separately.
Use try-except to keep your program running smoothly even when errors happen.
Summary
Exceptions help catch and handle errors in your code.
Common exceptions include ValueError, ZeroDivisionError, and IndexError.
Use try-except blocks to manage errors and keep your program running.