Exception Handling in Python – Detailed Notes
-What is an Exception?
An exception is an error that occurs while a program is running.
Example:
If you divide a number by 0, Python shows an error:
print(10
/ 0)
Error: ZeroDivisionError
-Why Do Exceptions Occur?
Exceptions happen when your program does something that is not allowed,
such as:
- Division by zero
- Using a variable that is not defined
- Opening a non-existent file
- Invalid input
-Why Do We Need Exception
Handling?
Without exception handling, the program stops immediately when an
error occurs.
Exception handling allows the program to:
-Continue running
-Separates error handling code from normal code
-Enhances readability
-Keywords used in Exception Handling:-
|
Keyword |
Meaning |
|
try |
The block of code where an exception may occur |
|
except |
Code that runs when an exception occurs |
|
else |
Runs when no exception occurs |
|
finally |
Always runs (with or without exception) |
- Broadly classified in two types:
1. Compile-time Error: Errors that occur due to the violation of programming language's grammar rules.
Example- Syntax errors like: print('X'+4)
2. Run-time Error: Errors that occur during runtime because of unexpected situations. This type of error is handled through exception handling.
- Syntax
try:
# code that may cause an error
except:
# code that runs if error occurs
1. Example
try:
a = int(input("Enter a no.="))
print("No. entered=", a)
except:
print("Invalid input. Please enter a
no.")
Explanation:
If the user enters a string or tuple or list or anything other than a number, error occurs.
Here except block handles the error and prints a message without stopping the program.
2. Handling Specific Exceptions
Example:
try:
a = int(input("Enter a number:
"))
b = int(input("Enter another number:
"))
print(a / b)
except
ValueError:
print("Please enter NUMBERS
only!")
except
ZeroDivisionError:
print("You cannot divide by
zero!")
3. Using 'else' Block
else runs only if no exception occurs.
try:
num = int(input("Enter a number+ "))
except:
print("Error! Not a number!")
else:
print("Success! You entered=",
num)
4. Using finally Block
finally runs every time, even if there is an error.
try:
print("Trying to divide...")
result = 10 / 0
except:
print("An error occurred.")
finally:
print("End of program.")
Output:
Trying
to divide...
An
error occurred.
End
of program.
5. Multiple Exceptions Together
try:
x = int(input("Enter a number="))
y = int(input("Enter another number="))
print("Result=", x / y)
except
(ValueError, ZeroDivisionError):
print("Error!Either wrong input or
division by zero!")
6. Raising an Exception externally
You can create your own errors using raise.
age
= int(input("Enter age: "))
if
age < 0:
raise ValueError("Age cannot be
negative!")
else:
print("Valid age:", age)
- Summary Table
|
Keyword |
Purpose |
|
try |
Place code that may cause error |
|
except |
Handle the error |
|
else |
Runs if no error occurs |
|
finally |
Always runs |
Program Using Exception
Handling
try:
num = int(input("Enter a number:
"))
print("Square:", num * num)
except
ValueError:
print("Please enter a valid number
only!")
-Exception Types in Python – Detailed Notes
Python has many built-in exception types, each describing a
different kind of error.
When something goes wrong during program execution, Python raises (creates) an exception object of a
particular type.
- What is an Exception Type?
An exception
type tells us what kind of error occurred.
Example:
ZeroDivisionError = Error caused by
dividing by zero
ValueError = Error caused by wrong
type of input
Each error has a name and purpose.
- Most Common Exception Types in Python
Below are the most important exception types, explained with simple examples.
- SyntaxError
Occurs when Python code has wrong syntax
(structure).
Example:
print("Hello"
Error:
SyntaxError: unexpected EOF while parsing
This happens before the program runs.
- NameError
Occurs when you use a variable that does not
exist.
Example:
print(x)
Error:
NameError: name 'x' is not defined
- TypeError
Occurs when an operation is used on the wrong type
of data.
Example:
print("5" + 5)
Error:
TypeError: can only concatenate str (not "int") to str
- ValueError
The data type is correct, but the value is wrong.
Example:
num = int("hello")
Error:
ValueError: invalid literal for int()
"hello" is a string but cannot be
converted to a number.
- IndexError
Occurs when accessing a list index that does not
exist.
Example:
fruits = ["apple", "banana"]print(fruits[5])
Error:
IndexError: list index out of range
- KeyError
Occurs when accessing a dictionary key that is not
present.
Example:
student = {"name": "Raj"}print(student["age"])
Error:
KeyError: 'age'
- ZeroDivisionError
Occurs when dividing by zero.
Example:
print(10 / 0)
Error:
ZeroDivisionError: division by zero
- FileNotFoundError
Occurs when trying to open a file that does not
exist.
Example:
f = open("abc.txt", "r")
Error:
FileNotFoundError: [Errno 2] No such file or directory
- AttributeError
Occurs when an object has no such attribute or
function.
Example:
x = 10x.append(5)
Error:
AttributeError: 'int' object has no attribute 'append'
- ImportError
Occurs when Python cannot import a module.
Example:
import mathsss
Error:
ImportError: No module named 'mathsss'
- Other Important Exception Types
|
Exception |
Meaning |
|
IndentationError |
Incorrect
indentation (spaces) |
|
RuntimeError |
Generic
error during execution |
|
MemoryError |
Program
runs out of memory |
|
OverflowError |
Number too
large to handle |
|
StopIteration |
Happens in
loops or iterators |
|
KeyboardInterrupt |
When user stops program (Ctrl+C) |
Example Showing Multiple Exceptions
Together
try: a = int(input("Enter number: ")) b = int(input("Enter divisor: ")) print(a / b) except ZeroDivisionError: print("Error: Cannot divide by zero.") except ValueError: print("Error: Please enter numbers only.") except Exception as e: print("Some other error occurred:", e)
# Exception is the base class of all
exceptions
- Summary Table of Common Exceptions
|
Exception |
Cause |
Example |
|
SyntaxError |
Wrong code
syntax |
Missing
bracket |
|
NameError |
Variable
not defined |
print(x) |
|
TypeError |
Wrong data
type |
"5"
+ 5 |
|
ValueError |
Wrong
value |
int("abc") |
|
ZeroDivisionError |
Divide by
zero |
10/0 |
|
IndexError |
Wrong list
index |
mylist[10] |
|
KeyError |
Missing
dictionary key |
dict["age"] |
|
FileNotFoundError |
File
missing |
open("abc.txt") |
|
AttributeError |
Missing
attribute |
10.append() |

