Unit -1 Chapter 1
Python – Errors and Exception Handling (Class 12 Notes)
1. What is an Error?
An error is a problem in a program that causes it to stop or behave unexpectedly.
Python errors are of two main types:
Types of Errors:
1. Syntax Errors
2. Exceptions (Runtime Errors)
2. Syntax Errors
• Errors in the structure of the code (spelling, missing colons, brackets, etc.).
• Python stops before running the program.
Example:
print("Hello) # missing closing bracket
Output:
SyntaxError: unterminated string literal at line 1
3. Exceptions (Runtime Errors)
• Errors that occur after the code starts running.
• Happen due to invalid actions like dividing by zero or using wrong data types.
Example:
a=5/0
Output:
ZeroDivisionError: division by zero
Vaibhav Chaudhary
PGT Computer Science
Unit -1 Chapter 1
4. Difference Between Syntax Error and Exception
Syntax Error Exception
Mistake in writing code Mistake during program execution
Detected before code runs Detected while code is running
Must be corrected to run the code Can be handled using try-except
5. Types of Exceptions
Built-in Exceptions in Python
These are errors that Python already knows about.
Exception Description Example
ZeroDivisionError Division by 0 10 / 0
ValueError Invalid value int("abc")
TypeError Wrong data type 5 + "hello"
IndexError Invalid list index a = [1]; a[2]
KeyError Dictionary key not found d = {}; print(d['x'])
FileNotFoundError File doesn’t exist open("no.txt")
NameError Using variable not defined print(x) if x is not defined
Vaibhav Chaudhary
PGT Computer Science
Unit -1 Chapter 1
User-Defined Exceptions
You can create your own exceptions by defining a class that inherits from Python's Exception
class.
Example 1:
class NegativeNumberError(Exception):
pass
number = -5
if number < 0:
raise NegativeNumberError("Negative numbers not allowed")
Example 2:
class TooShortError(Exception):
pass
name = "Al"
if len(name) < 3:
raise TooShortError("Name must be at least 3 letters")
6. Why Do We Need Exception Handling?
Without Handling:
• Code stops when error occurs
• Crashes the program
• Users get confused
With Handling:
• Prevents program from crashing
• Friendly error messages
• Continues program flow safely
Vaibhav Chaudhary
PGT Computer Science
Unit -1 Chapter 1
7. Throwing and Catching Exceptions
Throwing an Exception
Use the raise statement to throw an exception.
Example:
age = -1
if age < 0:
raise ValueError("Age cannot be negative")
Catching an Exception
Use the try-except block to catch and handle errors.
8. Raising Exceptions
a. raise Statement
Used to manually create (raise) an exception.
Example:
marks = -50
if marks < 0:
raise ValueError("Marks cannot be negative")
b. assert Statement
Used to check if a condition is true. If condition with assert statement is true then exception is
not raised, program executes normally but the condition with assert is false, it raises an
AssertionError.
Example:
age = -3
assert age >= 0, "Age cannot be negative"
Vaibhav Chaudhary
PGT Computer Science
Unit -1 Chapter 1
9. Handling Exceptions
Python uses the try-except block to catch and fix errors without crashing.
10. Catching Exceptions (Handling the exception:- use try except clause)
Try block:-
We write those statements in try block in which there is possibility of having /getting exceptions.
If any type of exception occurred in code written in try block during program execution then
program control goes to the corresponding except block written to handle that particular type of
exception.
Syntax:
try:
# risky code
except ExceptionType:
# handle the error
Except Block:-
Except block of a particular type is executed when an exception of that type occurred in try
block . When an exception is thrown in try block , control goes to the except block which
matches that exception . Then code written in except block is executed.
Multiple except block can be created each for different types of possible exceptions which may
be encountered in try block.
Example:
try:
x = int(input("Enter a number: "))
print(10 / x)
except ZeroDivisionError:
print("You can't divide by zero!")
Vaibhav Chaudhary
PGT Computer Science
Unit -1 Chapter 1
except ValueError:
print(“Enter a valid number”)
11. try-except-else Clause
• else runs only if no error occurred in try.
• When no exception occurs in try block then no except block executes. Then program
control goes to the else block and code of else block is executed.
Example:
try:
x = int(input("Enter a number: "))
except ValueError:
print("Invalid input!")
else:
print("You entered:", x)
If user enters a valid number value then exception is not raised and code of else block executes.
12. try-finally Clause
• finally block always runs, whether error occurs or not.
• Used for closing files, cleaning memory, etc.
Example:
try:
f = open("data.txt", "r")
print(f.read())
except FileNotFoundError:
Vaibhav Chaudhary
PGT Computer Science
Unit -1 Chapter 1
print("File not found.")
finally:
print("This block runs no matter what.")
13. Final Summary
Term Use
Try Write code that may cause error
Handle the error. Write those statements here which should be executed on
Except
getting exception.
Else Runs if no error occurs.
Finally Always runs regardless of whether exception occurs or not
Raise Manually raise an error/exception
Assert Raise error if condition is false
Exception
Base class for user-defined exceptions
class
Final Combined Example:
class AgeError(Exception):
pass
try:
age = int(input("Enter your age: "))
assert age > 0, "Age must be positive"
if age < 18:
raise AgeError("You must be 18 or older.")
Vaibhav Chaudhary
PGT Computer Science
Unit -1 Chapter 1
except ValueError:
print("Please enter a valid number!")
except AssertionError as e:
print("Assertion Error:", e)
except AgeError as e:
print("Custom Error:", e)
else:
print("Age is valid.")
finally:
print("Thank you for using the program.")
Vaibhav Chaudhary
PGT Computer Science