0% found this document useful (0 votes)
15 views10 pages

My Exception Handling

Uploaded by

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

My Exception Handling

Uploaded by

sanjay15482412
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

Exception Handling in Python

[ Exception Handling: Introduction, handling exceptions using try-except-finally blocks. ]

Exception:

 An exception is an Unexpected errors occurs during the runtime of a


program.
 An exception is a Python object that represents an error. When an error occurs during the execution of a
program, an exception is said to have been raised.
 An exception is defined as an unexpected condition/runtime error in a
program that causes the program’s flow to be interrupted.

* A syntax error occurs when any of the Python programming rules are violated or the program is not
written correctly as per the format required.

*Semantic Errors occur when the statement has no meaning in the program.
Example of Semantic Error
a=5 #Sattement 1
b=7 #Statement 2
a+b=res #Statement 3
“”” semantic error because an expression never comes to the left side of the
assignment operator. It should be always on the right side. “””
“Ayush is playing cricket.”
“Cricket is playing Ayush.”

try:
a=int(input("Enter any value: "))
b=int(input("Enter any value: "))
c=a/b
except ValueError:
print("Error..!!! Zero is the Denomenator")
except:
print("Any Other Error...")
else:
print("No Error and No Exception")
finally:
print("End of try ..... except with finally clause / always executed ")
try:
a=int(input("Enter any value: "))
b=int(input("Enter any value: "))
c=a/b
except ZeroDivisionError:
print("Error..!!! Zero is the Denomenator")
except ValueError:
print("Error...!! Value Error incorrect")
except TypeError:
print("Error...!! Incorrect Data Type")
else:
print("If no excpet is matchin then else will be executed..")
finally:
print("End of try ..... except with finally clause ")

print("End of the Program: ")

for k in range(8):
print(k)
try:
a=int(input("Enter any value: "))
b=int(input("Enter any value: "))
c=a/b
except ValueError:
print("Invalid Value Entered/Any Other Error...")
except ZeroDivisionError:
print(f"Error..!!! {a} Numerator {b} Denomenator Zero is the Denomenator")
except:
print(" Unexpected Error...!!!")
else:
print("No Error and No Exception")
finally:
print("End of try ..... except with finally clause / always executed ")
print("End of the program")
print("Program by: xyz")

 “ try …. except” statements are used to catch and handle exceptions in


Python. Statements that can raise exceptions are kept inside the try clause
and the statements that handle the exception are written inside except
clause.
Syntax:
try:
# There can be error code in this block / try block

except [exception name-1]:


# Do this to handle the exception;
# executed if the try block throws an error

except [exception name-2]:


# Do this to handle exception;
# executed if the try block throws an error
:
else:
# incase any other exception which are not specified then else will be executed
finally:
# Do this to handle exception;/ finally clause is optional with try.
# executed if the try block is there

Requirement of try…except:
 While writing or debugging a program, a user might doubt an exception to occur in a particular part
of the code. Such suspicious lines of codes are put inside a try block.

Try:
 Exceptions are caught in the try block handled in the except block.
 When an exception is encountered, further execution of the code inside the try block is stopped and the control
is transferred to the except block.
 Every try block is followed by an except block.
Except:

 The appropriate code to handle each of the possible exceptions (in the code inside the try block) are written
inside the except clause.

else
 We can put an optional else clause along with the try...except clause.
 An except block will be executed only if some exception is raised in the try block.
 But if there is no error then none of the except blocks will be executed.
 In this case, the statements inside the else clause will be executed.

Finally Clause
 finally clause is optional with try.
 finally block’s statements are always executed regardless of whether an exception has occurred in the try block
or not.
 finally statement should always be placed at the end of try clause, after all except blocks and the else block.

What is the use of else: Clause with try…except?

Ans:

- it is optional
- to display the message if there is no exception / Errors in the try block / exception defined doesn’t match.
- If any exception block is executed then else block will not be executed.

Raising Exceptions:

Each time an error is detected in a program, the Python interpreter raises


(throws) an exception. Exception handlers are designed to execute when
a specific exception is raised.
 raise Exception statement can be used to raise user defined
exception / error. It will interrupt / stop execution when it will be
fetched.
Syntax 1: raise exception-name[(optional argument)] # inbuilt exception
Syntax 2: raise Exception(“ user defined message”)
Example:

>>> raise Exception("Negative Number entered ")


>>> raise IndexError # inbuilt error

Example Code:

n=int(eval(input("Enter any value: ")))


if n<0:
raise Exception("Negative Number entered ")
else:
print(" Positive Number")

Example 2:

n=int(eval(input("Enter any value: "))) n=int(eval(input("Enter any value: ")))


if n==0: try:
raise Exception("Zero Entered ") if n==0:
elif n<0: raise Exception("Zero Entered ")
raise Exception("Negative Number ") elif n<0:
else: raise Exception("Negative Number ")
print(" Positive Number") else:
print("End of the Program: ") print(" Positive Number")
except:
print("Error....!!")
print("End of the Program: ")

Example 2:

try: try:
n=int(eval(input("Enter any value: "))) n=int(eval(input("Enter any value: ")))
if n==0: if n==0:
raise Exception("Zero Entered ") raise Exception #("Zero Entered ")
elif n<0: elif n<0:
raise Exception("Negative Number ") raise Exception #("Negative Number ")
else: else:
print(" Positive Number") print(" Positive Number")
except: except:
print("Zero Entered/ Negative Number") print("Error..!!! Exception Zero Entered/ Negative
finally: Number")
print("End of try ..... except with finally clause ") finally:
print("End of the Program: ") print("End of try ..... except with finally clause ")
print("End of the Program: ")

 Built-in Exceptions : Commonly occurring exceptions are usually defined in


the compiler/interpreter. These are called built-in exceptions.
Examples:
Built-in exceptions in Python:
Exception Explanation

SyntaxError It is raised when there is an error in the syntax of the Python code.

It is raised when a built-in method or operation mismatched or


inappropriate values are provided as input.
ValueError
a=int(input("Enter any value:"))
Enter any value:ram # input alphabet in place of digits

It is raised when the file specified in a program statement cannot


IOError
be opened.

It is raised when the user accidentally presses delete or esc key or


KeyboardInterrupt
cancels the execution.

It is raised when the specified module is not installed or not


ImportError
working.

It is raised when the end of file condition is reached without


EOFError
reading any data by input().

It is raised when any number is having denominator zero.


ZeroDivisionError
Example: >>> 50 / 0

It is raised when the index or subscript in a sequence is out of


IndexError
range. >>> s=”KVN” >>s[3] # Index Error

It is raised when a variable is accessed before declaration.


NameError
>>> v + 10 # v variable is not defined previously

IndentationError It is raised due to incorrect indentation in the program code.

It is raised when an operator is supplied with a value of incorrect


TypeError data type.
>>> 10 + ‘ram’

It is raised when the result of a calculation exceeds the maximum


OverFlowError
limit for numeric data type.
assert Statement:
An assert statement in Python is used to test an expression in the program code. If the result after testing
comes false, then the exception is raised.
Syntax: assert Expression[,arguments]
Example:
assert(number>=0), "OOPS... Negative Number"

Example code:
print("use of assert statement")

def negativecheck(number):
assert(number>=0), " OOPS... Negative Number by swasat"
print(number*number)

print (negativecheck(100))
print (negativecheck(-350))

Output:

a=int(input("Enter any value: "))

assert(a>=0), "OOPS... Negative Number by swasat"

b=int(input("Enter any value: "))

c=a/b

print("End of the program")

print("Program by: xyz")

WAP which will handle exception of Built-in exceptions type. “ZeroDivsiionError” and “Value Error”
print ("Handling multiple exceptions")
try:
numerator=50
denom=int(input("Enter the denominator: "))
print (numerator/denom)
print ("Division performed successfully")
except ZeroDivisionError:
print ("Denominator as ZERO is not allowed")
except ValueError:
print ("Only INTEGERS should be entered")
Output:

Handling multiple exceptions


Enter the denominator: 0
Denominator as ZERO is not allowed

# User defined Exception

class Zero_Ent(Exception):
"Raise when Zero is Entered"
pass
class Negative_Ent(Exception):
"Raise when Negative is Entered"
pass

try:
n=int(eval(input("Enter any value: ")))
if n==0:
raise Zero_Ent
elif n<0:
raise Negative_Ent
else:
print(" Positive Number")
except Zero_Ent:
print("Error Zero Entered")
except Negative_Ent:
print(Negative_Ent)
finally:
print("End of try ..... except with finally clause ")
print("End of the Program: ")
HOT

# define Python user-defined exceptions


class InvalidAgeException(Exception):
"Raised when the input value is less than 18"
pass

# you need to guess this number


number = 18

try:
input_num = int(input("Enter a number: "))
if input_num < number:
raise InvalidAgeException
else:
print("Eligible to Vote")

except InvalidAgeException:
print("Exception occurred: Invalid Age")

HOT

Find output of the following code:

try:

print("Start")

raise Exception("Custom_Error")

except Exception as e:

print("Error", str(e))

else:

print("Else part printed")

finally:

print("Final Block")
OUTPUT:

Start

Error Custom_Error

Final Block

Find output:

try:

print("Start")

# raise Exception("Custom_Error")

except Exception as e:

print("Error", str(e))

else:

print("Else part printed")

finally:

print("Final Block")

output:

Start

Else part printed

Final Block

You might also like