0% found this document useful (0 votes)
2 views8 pages

Exception Handling in Python Notes

This document provides an overview of exception handling in Python, explaining the types of exceptions, how to use try...except blocks, and the importance of handling exceptions to prevent program termination. It also covers built-in exceptions, the assert statement for debugging, and how to create user-defined exceptions for custom error handling. Examples illustrate the usage of these concepts in practical scenarios.

Uploaded by

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

Exception Handling in Python Notes

This document provides an overview of exception handling in Python, explaining the types of exceptions, how to use try...except blocks, and the importance of handling exceptions to prevent program termination. It also covers built-in exceptions, the assert statement for debugging, and how to create user-defined exceptions for custom error handling. Examples illustrate the usage of these concepts in practical scenarios.

Uploaded by

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

UNIT - II

Exception Handling in Python

Python Exceptions
An exception is an unexpected event that occurs during program execution.
For example,
divide_by_zero = 7 / 0
The above code causes an exception as it is not possible to divide a number by 0
Python Logical Errors (Exceptions)
Errors that occur at runtime (after passing the syntax test) are called exceptions or logical errors.
For instance, they occur when we
 try to open a file(for reading) that does not exist (FileNotFoundError)
 try to divide a number by zero (ZeroDivisionError)
 try to import a module that does not exist (ImportError) and so on.
Whenever these types of runtime errors occur, Python creates an exception object.
If not handled properly, it prints a traceback to that error along with some details about why that
error occurred.
Let's look at how Python treats these errors:
divide_numbers = 7 / 0
print(divide_numbers)
Output
Traceback (most recent call last):
File "<string>", line 1, in <module>
ZeroDivisionError: division by zero
Here, while trying to divide 7 / 0, the program throws a system exception ZeroDivisionError

Python Error and Exception


Errors represent conditions such as compilation error, syntax error, error in the logical part of the
code, library incompatibility, infinite recursion, etc.
Errors are usually beyond the control of the programmer and we should not try to handle errors.
Exceptions can be caught and handled by the program.

Python Exception Handling


exceptions abnormally terminate the execution of a program, it is important to handle exceptions.
In Python, we use the try...except block to handle exceptions.
Python try...except Block
The try...except block is used to handle exceptions in Python. Here's the syntax of try...except block:
try:
# code that may cause exception
except:
# code to run when exception occurs
Here, we have placed the code that might generate an exception inside the try block. Every try block
is followed by an except block.
When an exception occurs, it is caught by the except block. The except block cannot be used without
the try block.
Example: Exception Handling Using try...except
try:
numerator = 10
denominator = 0
result = numerator/denominator
print(result)
except:
print("Error: Denominator cannot be 0.")
# Output: Error: Denominator cannot be 0.

In the example, we are trying to divide a number by 0. Here, this code generates an exception.
To handle the exception, we have put the code, result = numerator/denominator inside the try block.
Now when an exception occurs, the rest of the code inside the try block is skipped.
The except block catches the exception and statements inside the except block are executed.
If none of the statements in the try block generates an exception, the except block is skipped.

Catching Specific Exceptions in Python


For each try block, there can be zero or more except blocks. Multiple except blocks allow us to
handle each exception differently.
The argument type of each except block indicates the type of exception that can be handled by it.
For example,
try:
even_numbers = [2,4,6,8]
print(even_numbers[5])
except ZeroDivisionError:
print("Denominator cannot be 0.")
except IndexError:
print("Index Out of Bound.")
# Output: Index Out of Bound

In this example, we have created a list named even_numbers.


Since the list index starts from 0, the last element of the list is at index 3. Notice the statement,
print(even_numbers[5])
Here, we are trying to access a value to the index 5. Hence, IndexError exception occurs.
When the IndexError exception occurs in the try block,
 The ZeroDivisionError exception is skipped.
 The set of code inside the IndexError exception is executed.

Python try...finally
In Python, the finally block is always executed no matter whether there is an exception or not.
The finally block is optional. And, for each try block, there can be only one finally block.
Example,
try:
numerator = 10
denominator = 0
result = numerator/denominator
print(result)
except:
print("Error: Denominator cannot be 0.")
finally:
print("This is finally block.")
Output
Error: Denominator cannot be 0.
This is finally block.
In the above example, we are dividing a number by 0 inside the try block. Here, this code generates
an exception.
The exception is caught by the except block. And, then the finally block is executed.

Python Built-in Exceptions


Legal operations can raise exceptions. There are plenty of built-in exceptions in Python that are
raised when corresponding errors occur.
We can view all the built-in exceptions using the built-in local() function as follows:
print(dir(locals()['__builtins__']))
Here, locals()['__builtins__'] will return a module of built-in exceptions, functions, and attributes
and dir allows us to list these attributes as strings.
Some of the common built-in exceptions in Python programming along with the error that cause
them are listed below:

Exception Cause of Error

AssertionError Raised when an assert statement fails.

AttributeError Raised when attribute assignment or reference fails.

FloatingPointError Raised when a floating point operation fails.

ImportError Raised when the imported module is not found.

IndexError Raised when the index of a sequence is out of range.

KeyError Raised when a key is not found in a dictionary.

KeyboardInterrupt Raised when the user hits the interrupt key (Ctrl+C or
Delete).

MemoryError Raised when an operation runs out of memory.

NameError Raised when a variable is not found in local or global scope.

NotImplementedErro Raised by abstract methods.


r

OverflowError Raised when the result of an arithmetic operation is too large


to be represented.

ReferenceError Raised when a weak reference proxy is used to access a


garbage collected referent.

RuntimeError Raised when an error does not fall under any other category.

StopIteration Raised by next() function to indicate that there is no further


item to be returned by iterator.

SyntaxError Raised by parser when syntax error is encountered.

IndentationError Raised when there is incorrect indentation.

TabError Raised when indentation consists of inconsistent tabs and


spaces.

SystemError Raised when interpreter detects internal error.


SystemExit Raised by [Link]() function.

UnboundLocalError Raised when a reference is made to a local variable in a


function or method, but no value has been bound to that
variable.

UnicodeTranslateErro Raised when a Unicode-related error occurs during


r translating.

ZeroDivisionError Raised when the second operand of division or modulo


operation is zero.

Python Assert Statement


Assertions are statements that assert or state a fact confidently in your program. For example, while
writing a division function, you're confident the divisor shouldn't be zero, you assert divisor is not
equal to zero.
Assertions are simply boolean expressions that check if the conditions return true or not. If it is
true, the program does nothing and moves to the next line of code. However, if it's false, the program
stops and throws an error.
It is also a debugging tool as it halts the program as soon as an error occurs and displays it.
We can be clear by looking at the flowchart below:

Python assert Statement


Python has built-in assert statement to use assertion condition in the program. assert statement
has a condition or expression which is supposed to be always true. If the condition is false assert
halts the program and gives an AssertionError.
Syntax for using Assert in Pyhton:
assert <condition>
assert <condition>,<error message>
In Python we can use assert statement in two ways as mentioned above.
1. assert statement has a condition and if the condition is not satisfied the program will stop
and give AssertionError.
2. assert statement can also have a condition and a optional error message. If the condition is
not satisfied assert stops the program and gives AssertionError along with the error
message.
Let's take an example, where we have a function that will calculate the average of the values passed
by the user and the value should not be an empty list. We will use assert statement to check the
parameter and if the length is of the passed list is zero, the program halts.
Example 1: Using assert without Error Message
def avg(marks):
assert len(marks) != 0
return sum(marks)/len(marks)
mark1 = []
print("Average of mark1:",avg(mark1))
Run Code
When we run the above program, the output will be:

AssertionError
We got an error as we passed an empty list mark1 to assert statement, the condition became false
and assert stops the program and give AssertionError.
Now let's pass another list which will satisfy the assert condition and see what will be our output.
Example 2: Using assert with error message
def avg(marks):
assert len(marks) != 0,"List is empty."
return sum(marks)/len(marks)
mark2 = [55,88,78,90,79]
print("Average of mark2:",avg(mark2))
mark1 = []
print("Average of mark1:",avg(mark1))
When we run the above program, the output will be:
Average of mark2: 78.0
AssertionError: List is empty.
We passed a non-empty list mark2 and also an empty list mark1 to the avg() function and we got
output for mark2 list but after that we got an error AssertionError: List is empty. The assert
condition was satisfied by the mark2 list and program to continue to run. However, mark1 doesn't
satisfy the condition and gives an AssertionError.
Python User Defined Exceptions
In Python, User-Defined Exceptions allow programmers to create their own custom exceptions
by deriving from the built-in Exception class. This is useful when you want to enforce application-
specific error handling.
Creating a User-Defined Exception
To define a custom exception:
1. Subclass the built-in Exception class.
2. Optionally, override the __init__ method to customize the message or store additional data.
3. Raise the exception when needed.

Example: Checking Age of the person


# Defining a custom exception
class AgeTooSmallError(Exception):
"""Custom exception for invalid age input."""
def __init__(self, message="Age entered is too small! Must be at least 18."):
[Link] = message
super().__init__([Link])
# Using the custom exception
try:
age = int(input("Enter your age: "))
if age < 18:
raise AgeTooSmallError # Raising the custom exception
print("Age is valid!")
except AgeTooSmallError as e:
print(f"Error: {e}")

Adding Custom Attributes


You can also include additional attributes to provide more context:
python
CopyEdit
class NegativeValueError(Exception):
"""Exception raised for negative values."""
def __init__(self, value):
[Link] = value
[Link] = f"Negative value entered: {value}. Only positive values are allowed."
super().__init__([Link])
try:
number = int(input("Enter a number: "))
if number < 0:
raise NegativeValueError(number)
print(f"Valid input: {number}")
except NegativeValueError as e:
print(f"Error: {e}")

Multiple Custom Exceptions


You can create multiple custom exceptions for different scenarios:
python
CopyEdit
class DivisionByZeroError(Exception):
pass
class ValueTooLargeError(Exception):
pass
try:
num = int(input("Enter a number: "))
if num == 0:
raise DivisionByZeroError("Cannot divide by zero!")
elif num > 100:
raise ValueTooLargeError("Value is too large!")
print(f"Valid number: {num}")
except (DivisionByZeroError, ValueTooLargeError) as e:
print(f"Exception: {e}")

You might also like