__author__ = "Narendra Boyina"
# -----------------------------------------------------------------------------
# Copyright (c) 2025 BR Technologies PVT LTD
# -----------------------------------------------------------------------------
"""
Topics to be covered in today's class:
--> what is exception ?
--> syntax of exception
--> Different types of exceptions in python
"""
"""
What is Exception?
When Python encounters an error, it raises an exception,
which can interrupt the normal flow of the program unless it is properly handled.
Common Causes of Exceptions:
--> Dividing by zero
--> Accessing a file that doesn’t exist
--> Referencing a variable that hasn’t been defined
--> Using the wrong type of data
"""
"""
Syntax
Here is simple syntax of try....except...else..finally blocks −
try:
We will implement the suspicious code (main logic) that may cause an error.
If an error occurs, it will be handled in the except block;
otherwise, the statements in the try block will execute as usual.
......................
except ExceptionI:
Except block handles errors from the try block and displays the error message on the console.
If there is ExceptionI, then execute this block of statements.
except ExceptionII:
If there is ExceptionII, then execute this block of statements.
......................
else:
If there is no exception then execute this block of statements.
finally:
The finally block allows you to execute code, regardless of the result of the try and except blocks.
"""
def add(a,b):
print(a+b)
# add(2.4, 4.2) # 2 float input values
# add(2, 4) # 2 integer input values
# add(-2, -4) # 2 negative integer input values
# add(2, 2.4) # 1 integer input value 1 float input value
# add("Polagani", "Subrahmanyam") # 2 string input values
# add("7", 3) # you have provided wrong values , please provide proper input values
# print("Narendra")
# print("Surendra")
# Exception handling for above logic
def add(a, b):
try:
print(a+b)
# except TypeError:
# print("user provided incorrect values")
# except ValueError:
# print("user provided wrong values")
# except TypeError as type_error_info:
# print(type_error_info)
# except ValueError as val_error:
# print(val_error)
# except AttributeError as err_info:
# print(err_info)
except Exception as error_info:
print(error_info)
else:
print("No exception occurred ")
finally:
print("this is finally block")
print("RAJ")
# add(2, 4)
# add(2, "MahaLakshmi")
# print("Narendra")
# print("Surendra")
"""
Example : 1
This example opens a file, writes content in the, file
and comes out gracefully because there is no problem at all −
"""
# fw = open("Narendra.txt", "r")
# fw.write("This is my test file for exception handling!!")
# try:
# fw = open("Narendra.txt", "r")
# fw.write("This is my test file for exception handling!!")
# except IOError as error_info:
# print(error_info)
# else:
# print ("Written content in the file successfully")
# fw.close()
#
# print("Jai")
# print("Abhishek")
"""
This produces the following result −
Written content in the file successfully
"""
"""
This example tries to open a file where you do not have the write permission, so it raises an exception −
"""
# try:
# fh = open("testfile.txt", "r")
# fh.write("Trying to write data in to the file")
# except Exception as file_error:
# print(file_error)
# else:
# print("Written content in the file successfully")
# finally:
# print("Jyothi")
# print("Kiran")
"""
This produces the following result −
Error: can't find file or read data
"""
# Argument of an Exception
def temp_convert(var):
try:
return int(var)
# except ValueError as jayanth:
# print("The argument does not contain numbers: ", jayanth)
# except TypeError as chandrika:
# print("**Type error:", chandrika)
except Exception as error_info :
print(error_info)
#
# Call above function here.
# x = temp_convert(12.5)
# x = temp_convert("12.5")
# y = temp_convert([1,2,4])
# print("value after converted is : {}".format(x))
# print(y)
# print("Manju")
# print("Narendra")
"""
Output
The argument does not contain numbers
invalid literal for int() with base 10: 'xyz'
Manju
"""
"""" Nested try block """
# try:
# fh = open("sai.txt", "r+")
# fh.write("This is outer try block")
# try:
# fh.seek(0,0)
# data = fh.read()
# print(data)
# fh.write("This is my test file for exception handling!!")
# except Exception as inner_error_info:
# print("inner exception occurred: ",inner_error_info)
# except Exception as outer_error_info:
# print ("outer exception occurred: ",outer_error_info)
# finally:
# print ("Going to close the file")
# print("Narendra")
# print("Meera")
"""Number of exceptions we can write in single program (Interpreter will handle based on Error)"""
# try:
# fh = open("testfile.txt", "r") #
# fh.write("This is my test file for exception handling!!")
# except IOError as Ierror:
# print ("if IO error occurred this statement will execute : ", Ierror)
# except ValueError as Verror:
# print("if Value error occurred this statement will execute :",Verror)
# except KeyError as x:
# print(x)
# else:
# print ("Written content in the file successfully")
# fh.close()
# finally:
# print("this is final block")
"""
How to handle any exception ? If we don't know which exception may occur
"""
# def add(a,b):
# try:
# print(a+b)
# except Exception as error_info:
# print(error_info)
#
#
# add(2, "Mahalakshmi")
daily_tasks = []
def read_lines(path):
try:
f_obj = open(path, "w")
for t in f_obj.readlines():
daily_tasks.append(t)
print(daily_tasks)
except Exception as Naziya:
print(Naziya)
# path = r"E:\Python Training\My Practice\BR_Techno_Solutions.txt"
# read_lines(path)
# print("Lakshmi")
# =====================================================================
"""
Different types of exceptions in python:
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:
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.
FilenotfoundError:
FilealreadyexistsError:
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.
"""Author: Boyina Narendra
Supporting Author: M. Meera Sindhu
Request: If you find this information useful, please provide your valuable comments
|
Python Built-in Exceptions |
|
|
Exception |
Cause of Error |
|
AssertionError |
Raised when assert statement
fails. |
|
AttributeError |
Raised when
attribute assignment or reference fails. |
|
EOFError |
Raised when
the input() functions
hits end-of-file condition. |
|
FloatingPointError |
Raised when a
floating point operation fails. |
|
GeneratorExit |
Raise when a
generator's close() method is
called. |
|
ImportError |
Raised when the
imported module is not found. |
|
IndexError |
Raised when 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 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. |
|
NotImplementedError |
Raised by
abstract methods. |
|
OSError |
Raised when
system operation causes system related error. |
|
OverflowError |
Raised when
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 sys.exit() function. |
|
TypeError |
Raised when a
function or operation is applied to an object of incorrect type. |
|
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. |
|
UnicodeError |
Raised when a
Unicode-related encoding or decoding error occurs. |
|
UnicodeEncodeError |
Raised when a
Unicode-related error occurs during encoding. |
|
UnicodeDecodeError |
Raised when a
Unicode-related error occurs during decoding. |
|
UnicodeTranslateError |
Raised when a
Unicode-related error occurs during translating. |
|
ValueError |
Raised when a
function gets argument of correct type but improper value. |
|
ZeroDivisionError |
Raised when
second operand of division or modulo operation is zero. |
No comments:
Post a Comment