Python try except finally

📔 : Python 🔗

पिछले topic में आपने Python में try except के बारे में पढ़ा , try except का use करके Exception को handle किया। इस topic में हम try except साथ finally block के बारे में पढ़ेंगे।


Exceptions / Run Time Errors को handle करने के लिए हम अपना code try block के अंदर लिखते थे , अगर error आती थी तो उस error को except block में handle करते थे। कई बार ऐसी situation आती है कि code को दोनों conditions में Run करना हो , means Exceptions आये तब भी code Run हो और न आये तब भी, वहाँ पर हम finally block use करते हैं।


finally block , try या except block के बाद हमेशा run होता है।

  1. अगर कोई Exceptions नहीं है तो try block के बाद run होगा ,
  2. और Exceptions आयी तो except block के बाद।

Python try except finally Syntax

try : 
    #code
except :
    #handle errror
finally :
    #code that runs always   

? try except की तरह ही try except finally भी सिर्फ Run Time Errors (जिन्हे Exception कहते हैं) में ही काम करता है , Syntax Error या Logical Errors को नहीं। अगर program में syntactically error है तो उसके लिए यह काम नहीं करेगा।

Python try except finally Example

Copy Fullscreen Close Fullscreen Run
try :
	print(name) #print an undefined variable.
except :
	print('Error occured')
finally :
	print('it will run always')
Output
C:\Users\Rahulkumar\Desktop\python>python try_except_finally.py
Error occured
it will run always

Python Custom Error

Python हमें ये functionality provide करती है कि हम custom exception generate कर सके। custom error generate करने के लिए raise keyword का use करते हैं। उसके बाद जिस name की error error generate करनी हो उस class का name .


बैसे by default सभी error classes Exception class को ही extend करती है , तो आप यह भी use कर सकते हो।

Python Custom Error Example

Copy Fullscreen Close Fullscreen
name = input('Enter any name :')

#check if entered name is not string.
if not type(name) is str:
  #raise an error.
  raise TypeError("Enter only string")

print('Hello :', name)
Output
C:\Users\Rahulkumar\Desktop\python>python custom_error.py
Enter any name :rahul Kumar
Hello : rahul Kumar

ऊपर दिए गए example में अगर आप string के अलावा कुछ enter करेंगे तो custom error generate हो जायगी।

Related Topics :

Rahul Kumar

Rahul Kumar

Hi ! I'm Rahul Kumar Rajput founder of learnhindituts.com. I'm a software developer having more than 4 years of experience. I love to talk about programming as well as writing technical tutorials and blogs that can help to others. I'm here to help you navigate the coding cosmos and turn your ideas into reality, keep coding, keep learning :)

Get connected with me. :) LinkedIn Twitter Instagram Facebook

b2eprogrammers