Exception Handling
Exception Handling in Python
1. Built-in Exceptions
Python provides many predefined exceptions that occur during program execution when an error happens.
Common built-in exceptions include:
| Exception | Description |
|---|---|
ZeroDivisionError | Occurs when dividing by zero |
TypeError | Occurs when wrong data type is used |
ValueError | Occurs when invalid value is given |
IndexError | Occurs when index is out of range |
KeyError | Occurs when dictionary key is not found |
FileNotFoundError | Occurs when file does not exist |
Example:
a = 10
b = 0
print(a / b)
Output:
ZeroDivisionError: division by zero
2. Handling Exceptions
Exceptions can be handled using try and except blocks.
Syntax
try:
# code that may cause error
except ExceptionType:
# handling code
Example
try:
a = int(input("Enter a number: "))
b = int(input("Enter another number: "))
print(a / b)
except ZeroDivisionError:
print("Cannot divide by zero")
3. Exception with Arguments
Exceptions can pass arguments or messages to provide more details about the error.
Example
try:
x = int("hello")
except ValueError as e:
print("Error occurred:", e)
Output:
Error occurred: invalid literal for int()
Here e stores the exception message.
4. Raising Exceptions
Sometimes programmers intentionally generate exceptions using the raise keyword.
Syntax
raise ExceptionType("Error Message")
Example
age = int(input("Enter age: "))
if age < 18:
raise ValueError("Age must be 18 or above")
else:
print("Eligible")
5. User-Defined Exceptions
Programmers can create custom exceptions by creating a class derived from Exception.
Example
class InvalidMarks(Exception):
pass
marks = int(input("Enter marks: "))
try:
if marks > 100:
raise InvalidMarks
print("Marks accepted")
except InvalidMarks:
print("Marks cannot be greater than 100")
6. Assertions in Python
Assertions are used for debugging purposes to check whether a condition is true.
If the condition is false, Python raises an AssertionError.
Syntax
assert condition, "Error message"
Example
x = int(input("Enter a number: "))
assert x >= 0, "Number must be positive"
print("Number is:", x)
If a negative number is entered, the output will be:
AssertionError: Number must be positive
Comments
Post a Comment