0% found this document useful (0 votes)
3 views18 pages

Exception Handling in Python

This document provides comprehensive notes on exception handling in Python, including definitions, types of exceptions, and practical examples. It explains the use of try, except, else, and finally blocks, along with common exceptions and their handling. Additionally, it includes sample programs and CBSE exam tips relevant to Class XII Computer Science curriculum.

Uploaded by

reshmi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views18 pages

Exception Handling in Python

This document provides comprehensive notes on exception handling in Python, including definitions, types of exceptions, and practical examples. It explains the use of try, except, else, and finally blocks, along with common exceptions and their handling. Additionally, it includes sample programs and CBSE exam tips relevant to Class XII Computer Science curriculum.

Uploaded by

reshmi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Exception Handling in Python (CBSE Class

XII Notes)

Exception Handling
What is an Exception?
An exception is an error that occurs during the execution of a program, causing the normal
flow of the program to stop.

Example:

a = 10
b = 0
print(a / b)

Output

ZeroDivisionError: division by zero

Error vs Exception
Error Exception
Occurs due to syntax mistakes. Occurs during program execution.
Program does not start. Program starts but stops when exception occurs.
Cannot be handled using try-except. Can be handled using try-except.

Example of Error
if x == 5
print(x)

Output

SyntaxError

Example of Exception
a = 5
b = 0
print(a / b)

Output
ZeroDivisionError

Why Exception Handling?


 Prevents program from crashing.
 Displays meaningful error messages.
 Improves reliability of programs.
 Allows the remaining part of the program to execute.

Types of Exceptions (Important for CBSE)


Exception Cause
ZeroDivisionError Division by zero
NameError Variable not defined
TypeError Wrong data type used
ValueError Invalid value
IndexError List index out of range
KeyError Dictionary key not found
FileNotFoundError File does not exist
ImportError Module cannot be imported
AttributeError Invalid attribute/method
EOFError No input received

try Block
The try block contains the code that may generate an exception.

Syntax

try:
statement(s)

Example

try:
num = 10 / 0
except:
print("Error occurred")

Output

Error occurred
except Block
Handles the exception generated inside the try block.

Syntax

try:
statements
except:
statements

Example

try:
a = 10
b = 0
print(a / b)
except:
print("Cannot divide by zero")

Output

Cannot divide by zero

Handling Specific Exceptions


Syntax

try:
statements
except ExceptionName:
statements

Example

try:
a = 10
b = 0
print(a / b)
except ZeroDivisionError:
print("Division by zero is not allowed")

Output

Division by zero is not allowed

Multiple except Blocks


Used when different exceptions may occur.
Example

try:
a = int(input("Enter a number: "))
print(10 / a)

except ZeroDivisionError:
print("Division by zero")

except ValueError:
print("Invalid input")

except Exception as e
Stores the exception object in a variable.

Example

try:
a = 10 / 0

except Exception as e:
print(e)

Output

division by zero

else Block
The else block executes only if no exception occurs.

Syntax

try:
statements

except:
statements

else:
statements

Example

try:
a = 20
b = 5
print(a / b)

except ZeroDivisionError:
print("Error")

else:
print("Division successful")

Output

4.0
Division successful

finally Block
The finally block executes whether an exception occurs or not.

Used for cleaning up resources like closing files or database connections.

Syntax

try:
statements

except:
statements

finally:
statements

Example

try:
print(10 / 2)

except:
print("Error")

finally:
print("Program Finished")

Output

5.0
Program Finished

Complete Example
try:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = a / b

except ZeroDivisionError:
print("Cannot divide by zero")

except ValueError:
print("Please enter integers only")

else:
print("Answer =", c)

finally:
print("Execution Completed")

raise Statement
Used to generate an exception manually.

Syntax

raise ExceptionName("Message")

Example

age = int(input("Enter age: "))

if age < 18:


raise ValueError("Age must be 18 or above")

Output

ValueError: Age must be 18 or above

Commonly Used Exceptions


# ZeroDivisionError
print(10/0)
# NameError
print(x)
# TypeError
print("10" + 5)
# ValueError
int("abc")
# IndexError
a = [1,2,3]
print(a[5])
# KeyError
d = {"A":10}
print(d["B"])

Flow of Exception Handling


Start


try Block


Exception?
┌───────┴────────┐
│ │
No Yes
│ │
▼ ▼
else except
│ │
└───────┬────────┘

finally


End

CBSE Important Programs


Program 1 – Handle Division by Zero
try:
a = int(input("Enter numerator: "))
b = int(input("Enter denominator: "))
print("Result =", a / b)

except ZeroDivisionError:
print("Division by zero not possible")

Program 2 – Handle Invalid Input


try:
n = int(input("Enter a number: "))
print(n)

except ValueError:
print("Invalid integer")

Program 3 – Multiple Exceptions


try:
a = int(input())
print(10 / a)

except ZeroDivisionError:
print("Cannot divide by zero")

except ValueError:
print("Invalid input")
Program 4 – else and finally
try:
x = int(input())
y = int(input())
print(x / y)

except ZeroDivisionError:
print("Division by zero")

else:
print("Executed successfully")

finally:
print("Program Ended")

CBSE Viva Questions


1. What is an exception?
2. Differentiate between Error and Exception.
3. Why is exception handling required?
4. What is the purpose of the try block?
5. What is the use of the except block?
6. When is the else block executed?
7. Does the finally block always execute?
8. What is the purpose of the raise statement?
9. How do you handle multiple exceptions?
10. What is the difference between except: and except Exception as e:?

CBSE Exam Tips


 Use specific exceptions (e.g., ZeroDivisionError, ValueError) instead of a generic
except whenever possible.
 Remember the order:
try → except → else → finally
 else runs only if no exception occurs.
 finally always executes, whether an exception occurs or not.
 raise is used to manually generate an exception.

……………………………………..

Programs
Here are CBSE Class XII Computer Science (Python) - Important Exception Handling
Programs that are frequently asked in CBSE board exams, sample papers, and competency-
based questions.

1. Handle Division by Zero (Very Important


⭐⭐⭐)
try:
a = int(input("Enter numerator: "))
b = int(input("Enter denominator: "))
print("Result =", a / b)

except ZeroDivisionError:
print("Cannot divide by zero.")

2. Handle Invalid Integer Input


(ValueError) ⭐⭐⭐
try:
age = int(input("Enter age: "))
print("Age =", age)

except ValueError:
print("Please enter a valid integer.")

3. Multiple Exceptions ⭐⭐⭐⭐


try:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print(a / b)

except ZeroDivisionError:
print("Division by zero is not allowed.")

except ValueError:
print("Invalid input.")

4. Using else Block ⭐⭐⭐


try:
a = int(input())
b = int(input())
c = a / b
except ZeroDivisionError:
print("Cannot divide.")

else:
print("Answer =", c)

5. Using finally Block ⭐⭐⭐⭐


try:
x = int(input())
y = int(input())
print(x / y)

except ZeroDivisionError:
print("Division by zero.")

finally:
print("Program Ended")

6. Complete Program (try + except + else +


finally) ⭐⭐⭐⭐⭐
try:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
result = a / b

except ZeroDivisionError:
print("Cannot divide by zero.")

except ValueError:
print("Enter only integers.")

else:
print("Result =", result)

finally:
print("Execution completed.")

7. NameError Handling ⭐⭐
try:
print(value)

except NameError:
print("Variable is not defined.")
8. IndexError ⭐⭐⭐
try:
L = [10, 20, 30]
print(L[5])

except IndexError:
print("Index out of range.")

9. KeyError ⭐⭐
try:
d = {"A": 10, "B": 20}
print(d["C"])

except KeyError:
print("Key not found.")

10. FileNotFoundError ⭐⭐⭐


try:
f = open("[Link]", "r")
print([Link]())
[Link]()

except FileNotFoundError:
print("File does not exist.")

11. Generic Exception ⭐⭐⭐


try:
a = int(input())
b = int(input())
print(a / b)

except Exception as e:
print("Error:", e)

12. Raise Exception ⭐⭐⭐⭐


age = int(input("Enter age: "))

try:
if age < 18:
raise ValueError("Age should be 18 or above.")
print("Eligible")
except ValueError as e:
print(e)

13. Password Validation ⭐⭐⭐⭐


(Competency-Based)
password = input("Enter password: ")

try:
if len(password) < 8:
raise ValueError("Password should contain at least 8 characters.")
print("Password Accepted")

except ValueError as e:
print(e)

14. Positive Number Check ⭐⭐⭐


num = int(input("Enter a number: "))

try:
if num < 0:
raise ValueError("Negative number not allowed.")
print("Number =", num)

except ValueError as e:
print(e)

15. Calculator Using Exception Handling


⭐⭐⭐⭐⭐
try:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
op = input("Enter operator (+,-,*,/): ")

if op == "+":
print(a + b)

elif op == "-":
print(a - b)

elif op == "*":
print(a * b)

elif op == "/":
print(a / b)

else:
raise ValueError("Invalid Operator")

except ZeroDivisionError:
print("Cannot divide by zero.")

except ValueError as e:
print(e)

CBSE Board Practice Questions


1-Mark Questions

1. What is an exception?
2. Differentiate between Error and Exception.
3. Name any two built-in exceptions.
4. Which block always executes?
5. What is the purpose of the raise statement?

2-Mark Questions

1. Write a program to handle ZeroDivisionError.


2. Explain the use of the else block with an example.
3. Explain the use of the finally block with an example.
4. Write a program to handle ValueError.

3-Mark Questions

1. Write a program to handle both ValueError and ZeroDivisionError.


2. Explain the flow of try, except, else, and finally using a program.
3. Write a Python program that accepts two numbers and displays their division using
exception handling.

5-Mark Questions

1. Write a menu-driven calculator using exception handling.


2. Develop a Python program using try, except, else, and finally blocks to perform
division and handle appropriate exceptions.

Most Important Programs for CBSE 2026 (Priority)


⭐⭐⭐⭐⭐

 Multiple Exception Handling (ZeroDivisionError + ValueError)


 try-except-else-finally
 Calculator using Exception Handling
 raise Statement
 Generic Exception (except Exception as e)
⭐⭐⭐⭐

 FileNotFoundError
 IndexError
 Division by Zero
 Invalid Integer Input

Ans

1-Mark Questions
1. What is an exception?

Answer:
An exception is a runtime error that occurs during the execution of a program and interrupts
its normal flow.

2. Differentiate between Error and Exception.

Error Exception
Occurs due to syntax mistakes. Occurs during program execution.
Program does not execute. Program starts but stops when an exception occurs.
Cannot be handled using try-except. Can be handled using try-except.

3. Name any two built-in exceptions.

Answer:

 ZeroDivisionError
 ValueError

Other examples: IndexError, TypeError, KeyError, NameError, FileNotFoundError.

4. Which block always executes?

Answer:
The finally block always executes, whether an exception occurs or not.

5. What is the purpose of the raise statement?


Answer:
The raise statement is used to manually generate an exception in a program.

Example:

raise ValueError("Invalid Input")

2-Mark Questions
1. Write a program to handle ZeroDivisionError.
try:
a = int(input("Enter numerator: "))
b = int(input("Enter denominator: "))
print("Result =", a / b)

except ZeroDivisionError:
print("Division by zero is not allowed.")

2. Explain the use of the else block with an example.


Answer:

The else block executes only if no exception occurs in the try block.

Example:

try:
a = 10
b = 2
print(a / b)

except ZeroDivisionError:
print("Cannot divide by zero.")

else:
print("Division Successful")

Output

5.0
Division Successful

3. Explain the use of the finally block with an example.


Answer:
The finally block executes whether an exception occurs or not. It is mainly used to
release resources such as closing files or database connections.

Example:

try:
print(10 / 2)

except ZeroDivisionError:
print("Error")

finally:
print("Program Ended")

Output

5.0
Program Ended

4. Write a program to handle ValueError.


try:
age = int(input("Enter age: "))
print("Age =", age)

except ValueError:
print("Please enter a valid integer.")

3-Mark Questions
1. Write a program to handle both ValueError and
ZeroDivisionError.

try:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("Result =", a / b)

except ValueError:
print("Invalid Input")

except ZeroDivisionError:
print("Division by zero is not allowed.")

2. Explain the flow of try, except, else, and finally using a


program.
Answer:
 try → Contains code that may generate an exception.
 except → Handles the exception.
 else → Executes if no exception occurs.
 finally → Executes whether an exception occurs or not.

Example:

try:
a = int(input("Enter numerator: "))
b = int(input("Enter denominator: "))
result = a / b

except ZeroDivisionError:
print("Division by zero")

except ValueError:
print("Invalid input")

else:
print("Result =", result)

finally:
print("Program Finished")

3. Write a Python program that accepts two numbers and


displays their division using exception handling.
try:
x = int(input("Enter first number: "))
y = int(input("Enter second number: "))
print("Division =", x / y)

except ZeroDivisionError:
print("Cannot divide by zero.")

except ValueError:
print("Invalid Input")

5-Mark Questions
1. Write a menu-driven calculator using exception
handling.
try:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))

print("[Link]")
print("[Link]")
print("[Link]")
print("[Link]")
ch = int(input("Enter your choice: "))

if ch == 1:
print("Answer =", a + b)

elif ch == 2:
print("Answer =", a - b)

elif ch == 3:
print("Answer =", a * b)

elif ch == 4:
print("Answer =", a / b)

else:
print("Invalid Choice")

except ZeroDivisionError:
print("Division by zero is not allowed.")

except ValueError:
print("Please enter valid integers.")

2. Develop a Python program using try, except, else, and


finally blocks to perform division and handle appropriate

exceptions.
try:
num1 = int(input("Enter numerator: "))
num2 = int(input("Enter denominator: "))

result = num1 / num2

except ZeroDivisionError:
print("Cannot divide by zero.")

except ValueError:
print("Please enter only integers.")

else:
print("Division =", result)

finally:
print("Program Execution Completed")

You might also like