Exception handling is an essential part of writing robust Python code, as it helps programs manage errors gracefully rather than abruptly terminating. In this guide, we’ll explore the common types of exceptions in Python, such as SyntaxError
, TypeError
, IndexError
, and ZeroDivisionError
, among others, and provide examples of how each occurs in real-world scenarios.
We’ll also delve into the try
and except
blocks, which allow you to catch specific exceptions and handle them accordingly. Using these blocks ensures that your code can respond appropriately to a variety of runtime issues, such as invalid input or unavailable resources, without crashing. The finally
block is another useful tool in exception handling, allowing you to perform cleanup tasks, like closing files or releasing resources, regardless of whether an error occurred.
If there is syntax error in the code such as missing parenthesis,misspelt word.
Example1:
if x == 10
print(“x is 10”)
# Output: SyntaxError: invalid syntax
Example2:
#incompatible datatypes are added
parabola=10;
Str=”thenmozhi”
Print(parabola+str) // x and integer and str is an str incompatible datatypes
Example 3:
print(value)# Here we are using the variable before it has been defined.
# Output: NameError: name ‘value’ is not defined
Example 4:
numbers = [1, 2, 3] #here the idexes are 0 1,2 we are trying to access 5 index
print(numbers[5])
# IndexError: list index out of range
KeyError: ( accessing the invalid key in the dictionary)
Example 5:
my_dict = {“a”: 1, “b”: 2}
print(my_dict[“c”])
# Output: KeyError: ‘c’
Example 6:
int_value = int(“hello”)
# Output: ValueError: invalid literal for int() with base 10: ‘hello’
Example 7:
# Trying to access a nonexistent attribute
class Sample:
pass
obj = Sample()
obj.attribute
# Output: AttributeError: ‘Sample’ object has no attribute ‘attribute’
Example:
# Trying to open a nonexistent file
with open(“nonexistent_file.txt”, “r”) as file:
content = file.read()
# Output: IOError (or FileNotFoundError in Python 3): [Errno 2] No such file or directory: ‘nonexistent_file.txt’
Example:
# Attempting to divide by zero
result = 10 / 0
# Output: ZeroDivisionError: division by zero
# Trying to import a nonexistent module
import nonexistent_module
# Output: ImportError: No module named ‘nonexistent_module’
–—————————————————————————–
Syntax error: syntax error are arised due to any syntax error in the program.
Exception : it the case Exception it says that where the program is syntactically correct but code results in error is called Exception
mark = 2000
a = mark / 0
print(a)
try and except block:
In this block the program is to run smoothly eventhrough the error occurs
try:
number = int(input(“Enter a number: “))
result = 100 / number
print(f”Result: {result}”)
except ValueError:
# This block runs if there’s a ValueError (e.g., if input isn’t a number)
print(“Please enter a valid integer.”)
except ZeroDivisionError:
# This block runs if there’s a ZeroDivisionError (e.g., if the number is zero)
print(“Cannot divide by zero.”)
except Exception as e:
# This block runs for any other exceptions
print(f”An unexpected error occurred: {e}”)
finally:
# This block always runs, even if there’s an error
print(“Execution completed.”)
In Python, catching specific exceptions allows you to handle different error types individually and take appropriate action for each.
This improves error handling and gives more precise control over what happens when specific errors occur.
try:
numbers = [1, 2, 3]
index = int(input())
divisor = int(input())
result = 100 / divisor
print(f”Result: {result}”)
print(f”Number at index {index}: {numbers[index]}”)
except IndexError:
print(“Index out of range! Please enter a valid index.”)
except ZeroDivisionError:
# This block handles attempts to divide by zero
print(“Cannot divide by zero.”)
except ValueError:
print(“Invalid input! Please enter an integer.”)
except Exception as e:
# This catches any other unforeseen exceptions
print(f”An unexpected error occurred: {e}”)
finally:
print(“Execution completed.”)
TRY WITH FINALLY
Finally block always executed.
.
try:
print(“Trying to divide by zero.”)
result = 10 / 0
except ValueError:
print(“A ValueError occurred.”)
finally:
print(“This will always execute.”)
Use finally for actions you need to perform no matter what happens in the try block, such as:
Exception handling is a powerful feature in programming, but it also has some disadvantages. Here are a few key disadvantages to consider:
Indian Institute of Embedded Systems – IIES