Exception: Exception that means abnormal behaviour

Exception: When in program exception raised program terminated abnormal and rest of code not executed

Exception: In python exception that means error

In python two type of error

  • syntax error
  • runtime error is call exception

In python error handing useing 5 keyword

  • try
  • except
  • else,default except
  • finally
  • raise

Python Exception Handing

if we use Exception handing mechanism.Then in program exception raised, program terminated normally and rest of code executed

Without Exception Handing :Program terminated abnormal and rest of code not executed

print("hello 1")
print("hello 2")
print("hello 3")
print("hello 4")
print(10/0)
print("hello 5")
print("hello 6")
print("hello 7")
hello 1
hello 2
hello 3
hello 4
Traceback (most recent call last):
  File "b10.py", line 5, in 
    print(10/0)
ZeroDivisionError: division by zero

With Exception Handing :Program terminated normally and rest of code executed

try except block syntax in python

try:
	exceptional code, may be may not be
except exception_class_name as variable_name:
	this code executed when exception raised in try block
print("hello 1")
print("hello 2")
print("hello 3")
print("hello 4")
try:
	print(10/0)
except ZeroDivisionError as e:
	print(e)	
print("hello 5")
print("hello 6")
hello 1
hello 2
hello 3
hello 4
division by zero
hello 5
hello 6

if except block doesn't match, program terminated abnormal

print("hello 1")
print("hello 2")
print("hello 3")
print("hello 4")
try:
	print(10/0)
except TypeError as e:
	print(e)	
print("hello 5")
print("hello 6")
hello 1
hello 2
hello 3
hello 4
Traceback (most recent call last):
  File "b10.py", line 6, in 
    print(10/0)
ZeroDivisionError: division by zero

try,except and else block syntax in python

try:
	exceptional code, may be may not be
except exception_class_name as variable_name
	this code executed when exception raised in try block
else:
	this code executed when no exception raised in try block	

Exception handly by try,except and else block python

else block execute when no exception raised in python

print("Hello1")
try:
    print(10/0)
except ArithmeticError as e:
#ArithmeticError is parent class
# and ZeroDivisionError is child class
    print("Exception :",e)
else:
	print("if try block no exception")    
print("Rest of code")    
Hello1
Exception : division by zero
Rest of code

else block execute when no exception raised

print("Hello1")
try:
    print(10/5)
except ArithmeticError as e:
#ArithmeticError is parent class
# and ZeroDivisionError is child class
    print("Exception :",e)
else:
	print("if try block no exception")    
print("Rest of code")    
Hello1
2.0
if try block no exception
Rest of code

default block except we enter string

print("Hello1")
try:
	a=int(input("enter a number : "))
	print(10/a)
except ArithmeticError as e:
    print("Exception :",e)
except : 
	print("default exception")   
else:
	print("if try block no exception")    

print("Rest of code")
Hello1
enter a number : STRING
default exception
Rest of code

CASE 1 : Single try block and multiple except block with else

try:
	#print(10/0)
	#ZeroDivisionError : division by zero
	print(10/2)
	name="ASHU"
	print(name.len())
	#AttributeError: 'str' object has no attribute 'len' 
	print(len(name))
	#add="abc"+100
	#TypeError: can only concatenate str (not "int") to str
	add=200+100
	print(add) 
	message="keep moving"
	#print(message[15])
	#IndexError: string index out of range
	print(message[2])
	#print(message.index("ashu"))
	#ValueError: substring not found
	print(message.index("keep"))
except ZeroDivisionError as e:
    print("ZeroDivisionError :",e)
except AttributeError as e:
    print("AttributeError :",e)
except TypeError as e:
    print("TypeError :",e)
except IndexError as e:
    print("IndexError :",e)
except ValueError as e:
    print("ValueError :",e)    
else:
    print("no exception raised")        
5.0
AttributeError : 'str' object has no attribute 'len'

CASE 2 : Single try block and except block with else

try:
	#print(10/0)
	#ZeroDivisionError : division by zero
	print(10/2)
	name="ASHU"
	#print(name.len())
	#AttributeError: 'str' object has no attribute 'len' 
	print(len(name))
	#add="abc"+100
	#TypeError: can only concatenate str (not "int") to str
	add=200+100
	print(add) 
	message="keep moving"
	print(message[15])
	#IndexError: string index out of range
	#print(message[2])
	#print(message.index("ashu"))
	#ValueError: substring not found
	print(message.index("keep"))
except (ZeroDivisionError,AttributeError,TypeError,IndexError,ValueError) as e:
   print("exception :",e)   
else:
	print("no exception raised")            
5.0
4
300
exception : string index out of range

Exception with BaseException class

try:
	#print(10/0)
	#ZeroDivisionError : division by zero
	print(10/2)
	name="ASHU"
	#print(name.len())
	#AttributeError: 'str' object has no attribute 'len' 
	print(len(name))
	#add="abc"+100
	#TypeError: can only concatenate str (not "int") to str
	add=200+100
	print(add) 
	message="keep moving"
	#print(message[15])
	#IndexError: string index out of range
	print(message[2])
	print(message.index("ashu"))
	#ValueError: substring not found
	print(message.index("keep"))
except BaseException as e:
   print("exception :",e)   
else:
	print("no exception raised")    
5.0
4
300
e
exception : substring not found

Exception with Exception class

try:
	#print(10/0)
	#ZeroDivisionError : division by zero
	print(10/2)
	name="ASHU"
	#print(name.len())
	#AttributeError: 'str' object has no attribute 'len' 
	print(len(name))
	#add="abc"+100
	#TypeError: can only concatenate str (not "int") to str
	add=200+100
	print(add) 
	message="keep moving"
	#print(message[15])
	#IndexError: string index out of range
	print(message[2])
	print(message.index("ashu"))
	#ValueError: substring not found
	print(message.index("keep"))
except Exception as e:
   print("exception :",e)   
else:
	print("There is no exception raised")    
5.0
4
300
e
exception : substring not found

yes, you can change except block parent to child or child to parent exception order in python but except block order must be child to parent

NOTE:

In this example if you enter number 0 then ZeroDivisionError exception raise or if you enter string then ValueError exception

def getException():
	try:
		num=int(input("Please Enter a number :"))
		print(100/num)
	except ZeroDivisionError as e:
		print("Child Exception :",e)
	except BaseException as e:
		print("Parent Exception :",e)	
	else:
		print("There is no exceptio")
getException()				
Please Enter a number :0
Child Exception : division by zero
Please Enter a number :ashu
Parent Exception : invalid literal for int() with base 10: 'ashu'

Here change the exception order parent to child exception in python

def getException():
	try:
		num=int(input("Please Enter a number :"))
		print(100/num)
	except BaseException as e:
		print("Parent Exception :",e)
	except ZeroDivisionError as e:
		print("Child Exception :",e)
	else:
		print("There is no exceptio")
getException()
Please Enter a number :0
Parent Exception : division by zero
Please Enter a number :ashu
Parent Exception : invalid literal for int() with base 10: 'ashu'

nested try except block in pyhton

def getException():
	try:
		num=int(input("Please Enter a number :"))
		print(100/num)
		try:
			print("ashu"+9015)
		except TypeError as e:
			print("Inner try block exception:",e)
		else:
			print("There is no exceptio in inner try block")
		print("inner try block rest of code")	
	except (ZeroDivisionError,ValueError) as e:
		print("Outer try block exception:",e)
	else:
		print("There is no exceptio in Outer try block")
	print("Outer try block rest of code")	
getException()
Please Enter a number :0
Outer try block exception: division by zero
Outer try block rest of code
Please Enter a number :10
10.0
Inner try block exception: can only concatenate str (not "int") to str
inner try block rest of code
There is no exceptio in Outer try block
Outer try block rest of code

CASE 1

Exception with module in python

this source file save as module1.py that is call modules name

def getExcetionFuntion():
	print("ABC"+100)

this source file save as module2.py that is call modules name

from module1 import getExcetionFuntion
try:
	getExcetionFuntion()
except Exception as e:
	print(e)
else:
	print("There is no error in module1 function")
can only concatenate str (not "int") to str

CASE 2

this source file save as module1.py that is call modules name

def getExcetionFuntion():
	try:
		print("ABC"+"XYZ")
	except Exception as e:
		print(e)
	else:
		print("There is no error in module1 function")

this source file save as module2.py that is call modules name

from module1 import getExcetionFuntion
getExcetionFuntion()
ABCXYZ
There is no error in module1 function

finally with try except block in pyhton

try except and finally block syntax

try:
	exceptional code, may be may not be
except:
	this code executed when exception raised in try block
finally:
    always executed

CASE 1: valid

def getException():
	try:
		print("try block")
	except:
		print("except block")
	finally:
		print("finally block")			
getException()
try block
finally block

CASE 2: normal termination

def getException():
	try:
		print(10+"ashu")
	except:
		print("except block")
	finally:
		print("finally block")			
getException()
except block
finally block

CASE 3: abnormal termination

def getException():
	try:
		print(10+"ashu")
	except ZeroDivisionError as e:
		print("except block :",e)
	finally:
		print("finally block")			
getException()
finally block
Traceback (most recent call last):
  File "jbbexception7.py", line 8, in 
    getException()
  File "jbbexception7.py", line 3, in getException
    print(10+"ashu")
TypeError: unsupported operand type(s) for +: 'int' and 'str'

CASE 4: Invalid and abnormal termination

def getException():
	try:
		print(10+"ashu")
	except TypeError as e:
		print(name[2])
		print("except block:",e)
	finally:
		print("finally block")			
getException()
finally block
Traceback (most recent call last):
  File "jbbexception7.py", line 3, in getException
    print(10+"ashu")
TypeError: unsupported operand type(s) for +: 'int' and 'str'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "jbbexception7.py", line 9, in 
    getException()
  File "jbbexception7.py", line 5, in getException
    print(name[2])
NameError: name 'name' is not defined

only try with finally in pyhton

def getException():
	try:
		print("try block")
	finally:
		print("finally block")			
getException()
try block
finally block

In python finally block not executed in two case

CASE 1: if exception raised outside try block

print("ABC"+100)
def getException():
	try:
		print("try block")
	finally:
		print("finally block")			
getException()

CASE 1: if use os module

import os
def getException():
	try:
		print("try block")
		os._exit(0)
	finally:
		print("finally block")			
getException()
try block

python interview question

CASE 1:

def getException():
	try:
		print("XYZ"+1000)
		print("try Block")
	except:
		print(name)
		print("except Block")	
	finally:
		print(ar[0])
		print("finally block")
getException()

CASE 2:

def getException():
	try:
		return 1000
	except:
		return 2000
	finally:
		return 3000
print(getException())

CASE 3:

def getException():
	try:
		return 1000
	finally:
		return 3000
print(getException())

CASE 4:

def getException():
	try:
		return 1000
	except:
		return 2000
print(getException())

CASE 5:

def getException():
	try:
		print(10+"AS")
		return 1000
	except:
		return 2000
print(getException())

CASE 6:

def getException():
	try:
		return 1000
	except:
		return 2000
	else:
		return 4000	
	finally:
		return 3000
		
print(getException()

custome exception with raise keyword in python

def getException():
	try:
		#print("ASHU"+10)
		raise TypeError("my type error")
	except TypeError as e:
		print(e)
	else:
		print("There is no exception")
getException()

custome exception using parent class constrouctor

this source file save as module1.py that is call modules name

class ageForVoteException(Exception):
	def __init__(self,message):
		super().__init__(message)

this source file save as module2.py that is call modules name

from module1 import ageForVoteException
class ForVote:
	def __init__(self,age):
		try:
			if(age>=18):
				print("valid for vote")
			else:
				raise ageForVoteException("Invalid age for vote")
		except ageForVoteException as e:
			print("ageForVoteException :",e)
		else:
			print("There is no error")
age=int(input("Please Enter Your Age :"))
fv=ForVote(age)	
Please Enter Your Age :2
ageForVoteException : Invalid age for vote

custome exception using instance variable

class ageForVoteError(Exception):
	def __init__(self,message):
		self.message=message
from module1 import ageForVoteError
class ForVote:

	@staticmethod
	def getMyMethod(age):
		print("code start......")
		try:
			if(age>=18):
				print("valid for vote")
			else:
				raise ageForVoteError("Invalid age for vote")
		except ageForVoteError as e:
			print("ageForVoteError :",e)
		else:
			print("There is no error")
		print("Rest of code......")	
age=int(input("Please Enter Your Age :"))
ForVote.getMyMethod(age)			
Please Enter Your Age :1
code start......
ageForVoteError : Invalid age for vote
Rest of code......
TypeError : concat not possible
ValueError : conversion
NameError : name is not defined
unboundLocalError