CHAPTER 1 - EXCEPTION HANDLING CBSE 12 - NOTES
- Python
CHAPTER 1 - EXCEPTION HANDLING CBSE 12 - NOTES
Program without Exception Handling :
num1 = int(input("Enter first number"))
num2 = int(input("Enter Second number"))
result = num1 / num2
print("Result:", result)
Program with Exception Handling :
num1 = int(input("Enter first number"))
num2 = int(input("Enter Second number"))
try:
result = num1 / num2
print("Result:", result)
except ZeroDivisionError:
print ("You Can not divide a number by Zero....")
CHAPTER 1 - EXCEPTION HANDLING CBSE 12 - NOTES
Built in Exception :
Basic structure of exception handling
try:
# Code that may raise an exception
# ...
except SomeException:
# Handle the exception if it occurs
# ...
finally:
# Code that always runs, whether an
exception occurred or not
# ...
CHAPTER 1 - EXCEPTION HANDLING CBSE 12 - NOTES
The try statement works as follows.
✓ First, the try clause (the statement(s) between the try and except
keywords) is executed.
✓ If no exception occurs, the except clause is skipped and execution of
the try statement is finished.
✓ If an exception occurs which does not match the exception named in
the except clause, it is passed on to outer try statements; if no handler
is found, it is an unhandled exception and execution stops with a
message as shown above.
File handling steps:
CHAPTER 1 - EXCEPTION HANDLING CBSE 12 - NOTES
def divide_numbers(a, b):
try:
result = a / b
except ZeroDivisionError:
print("Error: Division by zero!")
result = None
except ValueError:
print("Error: Invalid input value!")
result = None
except TypeError:
print("Error: Invalid data type!")
result = None
except Exception as e:
print(f"An unexpected error occurred: {e}")
result = None
finally:
print("Exception Handing in Python...")
return result
# Example 1: Division without error
result1 = divide_numbers(10, 2)
print("Result 1:", result1)
# Example 2: Division by zero (ZeroDivisionError)
result2 = divide_numbers(5, 0)
print("Result 2:", result2)
# Example 3: Invalid input value (ValueError)
result3 = divide_numbers(10, "2")
print("Result 3:", result3)
# Example 4: Invalid data type (TypeError)
result4 = divide_numbers("10", 2)
print("Result 4:", result4)
CHAPTER 1 - EXCEPTION HANDLING CBSE 12 - NOTES
Sample Program :
def divide_numbers(a, b):
try:
result = a / b
except ZeroDivisionError:
print("Error: Division by zero!")
result = None
finally:
print("Notes Exception Handling in Python Class 12...")
# This code will always run, even if an exception occurred or not
return result
# Example 1: Division without error
result1 = divide_numbers(10, 2)
print("Result 1:", result1)
# Example 2: Division by zero (error)
result2 = divide_numbers(5, 0)
print("Result 2:", result2)
Raise program:
Number =[40,50,60,70]
Length=10
If length>len(Number):
raise IndexError
print(“no Execution”)
else:
print(length)