Python Material 2024 TOPIC 9
Python Material 2024 TOPIC 9
In Python, there are several built-in Python exceptions that can be raised when an error occurs during the
execution of a program. Here are some of the most common types of exceptions in Python:
• SyntaxError: This exception is raised when the interpreter encounters a syntax error in the code,
such as a misspelled keyword, a missing colon, or an unbalanced parenthesis.
• TypeError: This exception is raised when an operation or function is applied to an object of the
wrong type, such as adding a string to an integer.
• NameError: This exception is raised when a variable or function name is not found in the current
scope.
• IndexError: This exception is raised when an index is out of range for a list, tuple, or other
sequence types.
• KeyError: This exception is raised when a key is not found in a dictionary.
• ValueError: This exception is raised when a function or method is called with an invalid argument
or input, such as trying to convert a string to an integer when the string does not represent a valid
integer.
• AttributeError: This exception is raised when an attribute or method is not found on an object,
such as trying to access a non-existent attribute of a class instance.
• IOError: This exception is raised when an I/O operation, such as reading or writing a file, fails due
to an input/output error.
• ZeroDivisionError: This exception is raised when an attempt is made to divide a number by zero.
• ImportError: This exception is raised when an import statement fails to find or load a module.
These are just a few examples of the many types of exceptions that can occur in Python. It’s important to
handle exceptions properly in your code using try-except blocks or other error-handling techniques, in
order to gracefully handle errors and prevent the program from crashing.
Difference between Syntax Error and Exceptions
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Syntax Error: As the name suggests this error is caused by the wrong syntax in the code. It leads to the
termination of the program.
Example:
There is a syntax error in the code . The ‘if' statement should be followed by a colon (:), and
the ‘print' statement should be indented to be inside the ‘if' block.
Python
1
amount = 10000
2
if(amount > 2999)
3
print("You are eligible to purchase Dsa Self Paced")
Output:
Exceptions: Exceptions are raised when the program is syntactically correct, but the code results in an
error. This error does not stop the execution of the program, however, it changes the normal flow of the
program.
Example:
Here in this code as we are dividing the ‘marks’ by zero so a error will occur known as ‘ZeroDivisionError’.
‘ZeroDivisionError’ occurs when we try to divide any number by 0.
marks = 10000
a = marks / 0
print(a)
Output:
In the above example raised the ZeroDivisionError as we are trying to divide a number by 0.
Note: Exception is the base class for all the exceptions in Python. You can check the exception
hierarchy here. (https://docs.python.org/2/library/exceptions.html#exception-hierarchy)
Example:
1) TypeError: This exception is raised when an operation or function is applied to an object of the wrong
type. Here’s an example:
Here a ‘TypeError’ is raised as both the datatypes are different which are being added.
2 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
x=5
y = "hello"
z=x+y
output:
Traceback (most recent call last):
File "7edfa469-9a3c-4e4d-98f3-5544e60bff4e.py", line 4, in <module>
z=x+y
TypeError: unsupported operand type(s) for +: 'int' and 'str'
try catch block to resolve it:
The code attempts to add an integer (‘x') and a string (‘y') together, which is not a valid operation, and it
will raise a ‘TypeError'. The code used a ‘try' and ‘except' block to catch this exception and print an error
message.
x=5
y = "hello"
try:
z=x+y
except TypeError:
Output
Error: cannot add an int and a str
a = [1, 2, 3]
try:
except:
Output
Second element = 2
An error occurred
In the above example, the statements that can cause the error are placed inside the try statement (second
print statement in our case). The second print statement tries to access the fourth element of the list
which is not there and this throws an exception. This exception is then caught by the except statement.
def fun(a):
if a < 4:
b = a/(a-3)
print("Value of b = ", b)
try:
fun(3)
fun(5)
except ZeroDivisionError:
except NameError:
Output
ZeroDivisionError Occurred and Handled
If you comment on the line fun(3), the output will be
NameError Occurred and Handled
The output above is so because as soon as python tries to access the value of b, NameError occurs.
try:
c = ((a+b) / (a-b))
except ZeroDivisionError:
else:
5 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
print (c)
AbyB(2.0, 3.0)
AbyB(3.0, 3.0)
Output:
-5.0
a/b result in 0
Example:
The code attempts to perform integer division by zero, resulting in a ZeroDivisionError. It catches the
exception and prints “Can’t divide by zero.” Regardless of the exception, the finally block is executed and
prints “This is always executed.”
try:
k = 5//0
print(k)
except ZeroDivisionError:
finally:
Raising Exception
The raise statement allows the programmer to force a specific exception to occur. The sole argument in
raise indicates the exception to be raised. This must be either an exception instance or an exception class
(a class that derives from Exception).
This code intentionally raises a NameError with the message “Hi there” using the raise statement within
a try block. Then, it catches the NameError exception, prints “An exception,” and re-raises the same
exception using raise. This demonstrates how exceptions can be raised and handled in Python, allowing
for custom error messages and further exception propagation.
try:
except NameError:
raise
The output of the above code will simply line printed as “An exception” but a Runtime error will also occur
in the last due to the raise statement in the last line. So, the output on your command line will look like
Traceback (most recent call last):
File "/home/d6ec14ca595b97bff8d8034bbf212a9f.py", line 5, in <module>
raise NameError("Hi there") # Raise Error
NameError: Hi there