Exception Handling in Python – Complete Guide
Exception is an unexpected runtime error that occurs during program execution. Python provides a powerful system to handle such errors using try–except blocks so that the program does not stop unexpectedly.
A real-world project contains multiple modules. If one program fails due to an error, the entire project may crash. To avoid this failure, Python strongly recommends using exception handling in all important code blocks.
Why Exception Handling Is Important?
- Prevents application crashes
- Allows safe handling of unexpected errors
- Improves user experience with friendly error messages
- Protects data and program flow
- Handles hardware, network, OS, file errors, etc.
Basic Syntax of Exception Handling
1. Try–Except
try:
CODE BLOCK
except:
Error Message
2. Try–Except with Specific Exception Class
try:
CODE BLOCK
except ExceptionClass:
Error Message
3. Multiple Except Blocks
try:
CODE BLOCK
except ExceptionClass1:
Error Message 1
except ExceptionClass2:
Error Message 2
4. Try–Except–Finally
try:
CODE BLOCK
except ExceptionClass:
Error Message
finally:
Default block (always runs)
5. Try–Except–Else–Finally
try:
CODE BLOCK
except ExceptionClass:
Error Message
else:
Runs when no exception occurs
finally:
Runs every time
Example: Basic Exception Handling
try:
a = int(input("Enter first number"))
b = int(input("Enter second number"))
c = a / b
print(c)
except ZeroDivisionError:
print("Denominator cannot be zero")
Handling Multiple Exceptions
try:
a = int(input("Enter first number"))
b = int(input("Enter second number"))
c = a / b
print(c)
except ZeroDivisionError:
print("Denominator cannot be zero")
except ValueError:
print("Enter only numeric value")
print("Line1")
print("Line2")
Use of Finally Block
finally block always executes—whether an exception occurs or not. Useful for cleanup operations (closing file, disconnecting DB, etc.)
try:
a = int(input("Enter first number"))
b = int(input("Enter second number"))
print(a/b)
except ZeroDivisionError:
print("Denominator cannot be zero")
except ValueError:
print("Enter only numeric value")
finally:
print("Finally block executed")
Using Else Block
else executes only when no exception occurs.
try:
a = int(input("Enter first number"))
b = int(input("Enter second number"))
print(a/b)
except ZeroDivisionError:
print("Denominator cannot be zero")
except ValueError:
print("Enter only numeric value")
else:
print("NOT ANY ERROR")
finally:
print("finally")
Complete Program Using Try–Except Loop
flag = True
count = 0
while flag:
try:
a = int(input("Enter first number"))
b = int(input("Enter second number"))
print(a / b)
except ValueError:
print("Enter only numeric value")
except ZeroDivisionError:
print("Denominator cannot be zero")
else:
flag = False
finally:
count += 1
print("Number of attempts:", count)
User-Defined Exception in Python
Python allows us to create custom exception classes for specific application needs.
Syntax
class ClassName(Exception):
pass
Example: Salary Exception
class SalaryException(Exception):
pass
try:
sal = int(input("Enter employee salary:"))
if sal < 10000:
raise SalaryException
else:
print("Salary is", sal)
except SalaryException:
print("Salary should be above 10000")
raise keyword is used to manually throw an exception (similar to throw in Java).
Common Built-in Exceptions in Python
| Sr.No. | Exception Name & Description |
|---|---|
| 1 | Exception Base class for all exceptions |
| 2 | StopIteration Raised when iterator has no more items. |
| 3 | SystemExit Raised by sys.exit(). |
| 4 | StandardError Base class for built-in exceptions. |
| 5 | ArithmeticError Base for numeric operation errors. |
| 6 | OverflowError Numeric value exceeds limit. |
| 7 | FloatingPointError Floating point calculation failed. |
| 8 | ZeroDivisionError Division by zero. |
| 9 | AssertionError Assert statement fails. |
| 10 | AttributeError Attribute not found. |
| 11 | EOFError No input; end of file reached. |
| 12 | ImportError Import statement fails. |
| 13 | KeyboardInterrupt User presses Ctrl+C. |
| 14 | LookupError Base for indexing errors. |
| 15 | IndexError Invalid index used. |
| 16 | KeyError Dictionary key not found. |
| 17 | NameError Identifier not defined. |
| 18 | UnboundLocalError Local variable referenced before assignment. |
| 19 | EnvironmentError External environment failures. |
| 20 | IOError Input/output error (file not found etc.) |
| 21 | OS Error Operating system error. |
| 22 | SyntaxError Invalid Python syntax. |
| 23 | IndentationError Incorrect indentation. |
| 24 | SystemError Internal interpreter error. |
| 25 | SystemExit Program exit request. |
| 26 | TypeError Invalid type operation. |
| 27 | ValueError Correct type, wrong value. |
| 28 | RuntimeError General runtime failure. |
| 29 | NotImplementedError Abstract method not implemented. |
Assignments for Practice
- 1) Create Marksheet Program with all exception handling
- 2) Validate mobile number using user-defined exception
- 3) Calculator program with multiple exception blocks
- 4) Raise exception if student fees > 500000
- 5) Define 10 built-in exceptions with examples
44 Comments
doubt-how to execute following code
ReplyDeletedef foo():
try:
return 1
finally:
return 2
k = foo()
print(k)
doubt-sir if we write else after finally is it write or not
ReplyDeletetry:
1 / 0
except:
print('exception')
else:
print('else')
finally:
print('finally')
# Create user-defined exceptions when student fees are>500000 otherwise display fees?
ReplyDeleteclass FeesException(Exception):
pass
try:
fees=int(input("enter fees of student"))
if fees<500000:
raise FeesException
else:
print("fees is "+str(fees))
except FeesException:
print("fees should be above 500000")
#Create a program for addition, subtraction, multiplication, and division using multiple exception block.
ReplyDeletetry:
a=int(input("enter value of a"))
b=int(input("enter value of b"))
c=a+b
print(c)
except ValueError:
print("value should be numeric")
try:
a=int(input("enter value of a"))
b=int(input("enter value of b"))
c=a-b
print(c)
except ValueError:
print("value should be numeric")
try:
a=int(input("enter value of a"))
b=int(input("enter value of b"))
c=a*b
print(c)
except ValueError:
print("value should be numeric")
try:
a=int(input("enter value of a"))
b=int(input("enter value of b"))
c=a/b
print(c)
except ZeroDivisionError:
print("denomentor not be zero")
1-exception LookupError
ReplyDeleteThis is the base class for those exceptions that are raised when a key or index used on a mapping or sequence is invalid or not found. The exceptions raised are :
KeyError
IndexError
try:
a = [1, 2, 3]
print (a[3])
except LookupError:
print ("Index out of bound error.")
else:
print ("Success")
2-exception EOFError
An EOFError is raised when built-in functions like input() hits an end-of-file condition (EOF) without reading any data. The file methods like readline() return an empty string when they hit EOF.
Example :
while True:
data = input('Enter name : ')
print ('Hello ', data)
exception FloatingPointError
3-A FloatingPointError is raised when a floating point operation fails.
import math
print (math.exp(1000))
4-exception KeyError
A KeyError is raised when a mapping key is not found in the set of existing keys.
array = { 'a':1, 'b':2 }
print (array['c'])
5-exception MemoryError
This error is raised when an operation runs out of memory.
Example :def fact(a):
factors = []
for i in range(1, a+1):
if a%i == 0:
factors.append(i)
return factors
num = 600851475143
print (fact(num))
6-exception NameError
This error is raised when a local or global name is not found. For example, an unqualified variable name.
def func():
print ans
func()
7-exception StopIteration
The StopIteration error is raised by built-in function next() and an iterator‘s __next__() method to signal that all items are produced by the iterator.
Example :
Arr = [3, 1, 2]
i=iter(Arr)
print (i)
print (i.next())
print (i.next())
print (i.next())
print (i.next())
8-A ZeroDivisionError is raised when the second argument of a division or modulo operation is zero.
print (1/0)
9-exception ValueError
A ValueError is raised when a built-in operation or function receives an argument that has the right type but an invalid value.
Example :print (int('a'))
10-exception TypeError
TypeError is raised when an operation or function is applied to an object of inappropriate type
arr = ('tuple', ) + 'string'
print (arr)
Chetan
ReplyDelete#A ZeroDivisionError is raised when the second argument of a division or modulo operation is zero.
print (1/0)
#exception ValueError
#A ValueError is raised when a built-in operation or function receives an argument that has the right type but an invalid value.
print (int('a'))
#exception TypeError
#TypeError is raised when an operation or function is applied to an object of inappropriate type
arr = ('aditya', ) + 'Chetan'
print (arr)#can only concatenate tuple (not "str") to tuple
Chetan
ReplyDelete#-exception EOFError
try:
n = int(input())
print(n * 10)
except EOFError as e:
print(e)
Chetan
ReplyDelete#-exception KeyError
#A KeyError is raised when a mapping key is not found in the set of existing keys.
array = { 'a':1, 'b':2 }
print (array['c'])
#because of c (key) is not in the array
Chetan
ReplyDelete#name_error
def msg():
try:
g = "Chetan"
return ge
except NameError:
return "Some variable isn't defined."
print(msg())
#WAP to validate mobile number using the Exception?
ReplyDeleteclass ValidateNumber(Exception):
pass
try:
num = int(input("Enter mobile number = "))
b = str(num)
c =len(b)
if c<10 or num == 0000000000 or num == 1234567890:
raise ValidateNumber
else:
print("Your number is " + b)
except ValueError:
print("Please Enter Number")
except ValidateNumber:
print("Enter Valid Number")
Chetan
ReplyDelete#SystemExit
#Raised when Python interpreter is quit by using the sys.exit() function.
#If not handled in the code, causes the interpreter to exit.
for i in range(10):
if i == 5:
try:
print("hello")
raise SystemExit
except BaseException:
print("It works!")
finally:
print(i)
'''
try:
raise SystemExit
except BaseException:
print("It works!")
'''
Chetan
ReplyDelete#syntax Error
print \\"Message")
#Indentation Error
ReplyDeletetry:
def f():
z=['foo','bar']
for i in z:
if i == 'foo':
except IndentationError as e:
print e
#Create a program for addition, subtraction, multiplication, and division using multiple exception block.
ReplyDeletetry:
a = int(input("Ente number = "))
b = int(input("Enter number = "))
add = a + b
sub = a-b
mul = a*b
div = a/b
except ValueError:
print("Enter Valid Number")
except ZeroDivisionError:
print("0 Denominator Not Allowed, Division is not possible")
except TypeError:
print("Enter Valid Number")
else:
print("No Error")
finally:
print("Addition is = ",add)
print("Substraction is = ",sub)
print("Multiplication = ",mul)
print("Division is = ",div)
#Create user-defined exceptions when student fees are>500000 otherwise display fees?
ReplyDeleteclass StudentFee(Exception):
pass
try:
fee = int(input("Enter Fee = "))
if fee >50000:
raise StudentFee
else:
print("Fee is = "+str(fee))
except StudentFee:
print("Fee should be below 50,000/-")
except ValueError:
print("Enter Valid Fee")
try:
ReplyDeletea = int(input("Enter number: "))
b = int(input("Enter number: "))
print("Result of Division: " + str(a/b))
except(ZeroDivisionError):
print("You have divided a number by zero, which is not allowed.")
print("Result of Addition: " + str(a+b))
print("Result of Multiplication: " + str(a*b))
print("Result of Substraction : " + str(a-b))
except(ValueError):
print("You must enter integer value")
i=1
ReplyDeletetry:
f = 3.0*i
for i in range(100):
print( i, f)
f = f ** 2
except OverflowError as err:
print ('Overflowed after ', f, err)
2.
ReplyDeleten = int(input("Please enter a number: "))
while True:
try:
n = input("Please enter an integer: ")
n = int(n)
break
except ValueError:
print("No valid integer! Please try again ...")
print("Great, you successfully entered an integer!")
3.
ReplyDeletetry:
a = int(input("Ente number = "))
b = int(input("Enter number = "))
add = a + b
sub = a-b
mul = a*b
div = a/b
except ValueError:
print("Enter Valid Number")
except ZeroDivisionError:
print("0 Denominator Not Allowed, Division is not possible")
except TypeError:
print("Enter Valid Number")
else:
print("No Error")
finally:
print("Addition is = ",add)
print("Substraction is = ",sub)
print("Multiplication = ",mul)
print("Division is = ",div)
4.
ReplyDeleteclass StudentFee(Exception):
pass
try:
fee = int(input("Enter Fee = "))
if fee >50000:
raise StudentFee
else:
print("Fee is = "+str(fee))
except StudentFee:
print("Fee should be below 50,000/-")
except ValueError:
print("Enter Valid Fee")
class fee(Exception):
ReplyDeletepass
try:
fe=int(input("enter fees of student"))
if fe<500000:
raise fee
else:
print(fe)
except fee:
print("fee should be greater than 500000")
try:
ReplyDeletea=int(input("enter 1st number"))
b=int(input("enter 2nd number"))
c=a+b
d=a-b
e=a*b
f=a/b
print("sum"+str(c)+"substraction"+str(d)+"multiplication"+str(e)+"division"+str(f))
except ZeroDivisionError:
print("Please do not enter zero number")
except ValueError:
print("please enter correct number")
class mException(Exception):
ReplyDeletepass
class sException(Exception):
pass
try:
s1=str(input("enter subject"))
m1=int(input("enter marks"))
s2=str(input("enter subject"))
m2=int(input("enter marks"))
s3=str(input("enter subject"))
m3=int(input("enter marks"))
s4=str(input("enter subject"))
m4=int(input("enter marks"))
s5=str(input("enter subject"))
m5=int(input("enter marrks"))
if m1>100 or m2>100 or m3>100 or m4>100 or m5>100:
raise mException
tm=m1+m2+m3+m4+m5
p=(tm*100)/500
if p>=75:
print("your percentage is"+str(p)+"your total marks"+str(tm)+"you pass with A grade")
if p>=60:
print("your percentage is"+str(p)+"your total marks"+str(tm)+"you pass with B grade")
if p>=45:
print("your percentage is"+str(p)+"your total marks"+str(tm)+"you pass with C grade")
if p>=33:
print("your percentage is"+str(p)+"your total marks"+str(tm)+"you pass with a grade")
else:
print("you are fail")
except mException:
print("marks should be out of 100")
except ValueError:
print("enter right subject name")
class no(Exception):
ReplyDeletepass
try:
x=input("enter mobile number")
c=0
for i in range(0,len(x)):
if ord(x[i])>=48 and ord(x[i])<=57:
c=c+1
if c<10 or c>10:
raise no
except no:
print("invalid mobile number")
else:
print("valid mobile number")
# valid mobile number
ReplyDeletetry:
num=str(input())
x=list(num)
c=len(x)
if c==10:
if (x[0]=="7" or x[0]=="8" or x[0]=="9"):
print("valid mobile number",num)
else:
print("not valid")
else:
print("mobile number should be of ten digit")
except ValueError as e:
print(e)
finally:
print("please enter valid number")
#WAP to validate mobile number
ReplyDeletetry:
num=str(input("Enter mobile number:"))
x=list(num)
c=len(x)
if c==13:
if (x[0]=="+91"):
print("Valid number",num)
if (x[1]=="7" or x[1]=="8" or x[1]=="9"):
print("valid mobile number",num)
else:
print("not valid")
else:
print("Invalid number")
except ValueError as e:
print(e)
#Create user-defined exceptions when student fees are>500000 otherwise display fees?
ReplyDeleteclass FeesException(Exception):
pass
try:
fees=int(input("Enter fees of student:"))
if fees>500000:
raise FeesException
else:
print("Fees is:"+str(fees))
except FeesException:
print("The amount should be less than 500000")
#Addition
ReplyDeletetry:
a=int(input("enter value of a"))
b=int(input("enter value of b"))
c=a+b
print(c)
except ValueError:
print("value should be numeric")
#Subtraction
try:
a=int(input("enter value of a"))
b=int(input("enter value of b"))
c=a-b
print(c)
except ValueError:
print("value should be numeric")
#Multiplication
try:
a=int(input("enter value of a"))
b=int(input("enter value of b"))
c=a*b
print(c)
except ValueError:
print("value should be numeric")
#Division
try:
a=int(input("enter value of a"))
b=int(input("enter value of b"))
c=a/b
print(c)
except ZeroDivisionError:
print("denominator should not be zero")
except ValueError:
print("value should be numeric")
#Execption on value error and zero division error
ReplyDeletetry:
a=int(input("enter first number"))
b=int(input("enter second number"))
c=a/b
print(c)
except ValueError:
print("enter numeric char only")
except ZeroDivisionError:
print("demonator can not be zero")
# try.....execpt=finally
ReplyDeletec=0
res=""
try:
a=40
b=50
c=a+b
res="sucess"
except:
print("invalid input")
res="fail"
finally:
print("result is",c)
print("program execution is",res)
1. Exception
ReplyDeletetry:
a=4
b="sgg"
c=a/b
print(c)
except Exception:
print("Default")
2. Airthmetic error :- Error in numeric calculation
try:
a = 10/0
print (a)
except ArithmeticError:
print ("This statement is raising an arithmetic exception.")
else:
print ("Success.")
3. OverFlowError - When calculation is exceeded to maximum limit
try:
import math
print(math.exp(10))
except OverflowError:
print("Error")
4. FloatingPointError : Failure in floating calculation
try:
a=1.3
b=1.1
c=a-b
print(c)
except FloatingPointError:
print("Error")
5. ZeroDivisionError: - Denominator should not be 0.
try:
a=10
b=0
c=a/b
print(c)
except ZeroDivisionError:
print("error")
6. AssertionError: - Failure of assertion statement
try:
x = 1
y = 3
assert y != 3, "Invalid Operation"
print(x / y)
except AssertionError:
print("Error")
7. AttributeError:- failure of attribute reference or assignment.
try:
class fg:
def __init__(self):
self.a ="byh"
obj = fg()
print(obj.a)
print(obj.b)
except AttributeError:
print("Error")
8. NameError: - when an identifier is not found in the local or global namespace.
try:
class fg:
def __init__(self):
self.a ="byh"
obj = java()
print(obj.a)
except AttributeError:
print("Error")
try:
ReplyDelete#Addition
a=int(input("enter number: "))
b=int(input("enter number: "))
c=a+b
print(c)
except ValueError:
print("value should be numeric")
print()
#Multiplication
try:
a=int(input("enter number: ")) #raise addException
b=int(input("enter number: "))
c=a*b
print(c)
except ValueError:
print("number should be numberic")
#Dvivision
a=int(input("enter number: "))
b=int(input("enter number: "))
s=a/b
print(s)
except ValueError:
print("denominator can not be zero")
print()
try:
a=int(input("enter number"))
b=int(input("enter number"))
c=a-b
print(c)
except ValueError:
print("value should be numeric")
# program of addition using multiple exception block.
ReplyDelete# Anjali verma
try:
a=int(input("enter first number"))
b=int(input("enter second number"))
c=a+b
print(c)
except ValueError:
print("enter only numeric value")
# program of subtraction using multiple exception block.
ReplyDelete# Anjali verma
try:
a=int(input("enter first number"))
b=int(input("enter second number"))
c=a-b
print(c)
except ValueError:
print("enter only numeric value")
# program of multiplication using multiple exception block.
ReplyDelete# Anjali verma
try:
a=int(input("enter first number"))
b=int(input("enter second number"))
c=a*b
print(c)
except ValueError:
print("enter only numeric value")
# program of division using multiple exception block.
ReplyDelete# Anjali verma
try:
a=int(input("enter first number"))
b=int(input("enter second number"))
c=a/b
print(c)
except ValueError:
print("denominator should not be zero")
#valid gmail
ReplyDeleteclass emailException(Exception):
pass
try:
email = input("enter email: ")
atpos = 0
dotpos = 0
i = 0
c = 0
for e in email:
if e==".":
dotpos=i
elif e=="@":
atpos=i
c=c+1
i=i+1
if atpos==0 or dotpos==0 or atpos>dotpos or c>1 or dotpos-atpos<2 or dotpos==len(email):
raise emailException
print("valid email",email)
except emailException:
print("invalid email",email)
try:
ReplyDeletea = int(input("Enter First Number "))
b = int(input("Enter Second Number "))
c = a/b
print(c)
except ZeroDivisionError:
print("denominator can not be zero")
# To validate email id
ReplyDeleteclass error(Exception):
pass
try:
a=input("enter email id:-")
b=a.count("@")
if b==0:
raise error("@ not present")
elif b==2:
raise error("only 1 @ is allowed but 2 given")
else:
d=a[a.find("@"):]
if d.count(".")>0:
if d.index(".")-d.index("@")>=6:
if len(d)-d.index(".")>=2:
raise error("Valid email id")
else:
raise error("after dot atleast 1 words should present")
else:
raise error("Required distance bewteen @ and . is less it should be atleast 5")
else:
raise error("ATLEAST DOT SHOULD PRESENT")
except error as e:
print(e)
#CHECK VALID MOBILE NUMBER
ReplyDeleteclass error(Exception):
pass
try:
a=input("enter mobile number:-")
if a.isnumeric()==False:
raise error("Alphabet not allowed")
else:
if len(a)==10:
print("Valid mobile number")
else:
raise error("Mobile number should consist 10 digit")
except Exception as e:
print(e)
Pawan Singh Rathore
ReplyDeleteBatch Python (11AM to 12PM)
class ValidMobileNumber(Exception):
pass
try:
a=input("enter mobile number:-")
if ((a >= 'a' and a <= 'z') or (a >= 'A' and a <= 'Z')):
raise ValidMobileNumber
elif len(a)==10:
print("Valid mobile number")
else:
raise ValidMobileNumber
except ValidMobileNumber:
print("Number should be 10 digit or Alphabet character not allowed")
Manage mark sheet program with all possible exception
ReplyDeleteclass mraskException(Exception):
pass
class subjectException(Exception):
pass
try:
sub1=str(input("enter subject"))
mrask1=int(input("enter marks"))
sub2=str(input("enter subject"))
mrask2=int(input("enter marks"))
sub3=str(input("enter subject"))
mrask3=int(input("enter marks"))
sub4=str(input("enter subject"))
mrask4=int(input("enter marks"))
sub5=str(input("enter subject"))
mrask5=int(input("enter marrks"))
if mrask1>100 or mrask2>100 or mrask3>100 or mrask4>100 or mrask5>100:
raise mraskException()
tm=mrask1+mrask2+mrask3+mrask4+mrask5
p=(tm*100)/500
if p>=75:
print("your percentage is"+str(p)+"your total marks"+str(tm)+"you pass with A grade")
elif p>=60 and p<=75:
print("your percentage is"+str(p)+"your total marks"+str(tm)+"you pass with B grade")
elif p>=45 and p<=60:
print("your percentage is"+str(p)+"your total marks"+str(tm)+"you pass with c grade")
elif p>=33 and p<=45:
print("your percentage is"+str(p)+"your total marks"+str(tm)+"you pass with D grade")
elif p<=32:
print("your percent is"+str(p)+"your total marsk"+str(tm)+"you are fail")
except mraskException():
print("marks should be out of 100")
except ValueError:
print("enter your only number for marsk")
WAP to validate mobile number using the Exception?
ReplyDeleteclass no(Exception):
pass
try:
x=input("enter mobile number")
c=0
for i in range(0,len(x)):
if ord(x[i])>=48 and ord(x[i])<=57:
c=c+1
if c<10 or c>10:
raise no
except no:
print("invalid mobile number")
else:
print("valid mobile number")
try:
ReplyDeletefirst=int(input("enter a first number"))
second=int(input("enter a second number"))
operator=input("enter a operator")
if operator=="+":
print(first + second)
if operator=="-":
print(first - second)
if operator=="*":
print(first * second)
if operator=="/":
print(first / second)
if operator=="%":
print(first % second)
except ZeroDivisionError:
print("Denominator Can't Be Zero")
except ValueError:
print("Print Only Numeric Value")
POST Answer of Questions and ASK to Doubt