Python में try except का use Run Time Errors को handle करने के लिए किया जाता है , ताकि program terminate न होकर normally run हो सके। इसमें try block में हम वो code लिखते हैं जिसमे error आने के chances होते हैं , और except block में वो code लिखते हैं जिसे error आने पर run करना है।

Python try except syntax

try :
    //code 
except :
    //error handling code

अगर try block में लिखे code में कोई error नहीं आती है, तो program normally run हो जायगा।

Python try except Example

Copy Fullscreen Close Fullscreen Run
try :
	print(name)
except :
	print('Error occured')
Output
C:\Users\Rahulkumar\Desktop\python>python exception_handle.py
Error occured

Handle More Than One Errors

आप error handle करने के लिए एक से ज्यादा except statement define कर सकते हैं। एक से जयदा error handle करने के लिए आपको एक से ज्यादा except statement लिखने पडते हैं।


basically जिस तरह से data type होते हैं वैसे ही हर error का एक particular type होता है। like : NameError, SyntaxError, etc.. except block एक optional argument accept करता है , जिसमे error का type pass होता है।


error आने पर जो type match कर जायगा वही except statement run हो जयगा।
See Example -

Copy Fullscreen Close Fullscreen Run
try:
  print(name)
except NameError:
  print("NameError occured")
except:
  print("Something else went wrong")
Output
C:\Users\Rahulkumar\Desktop\python>python exception_handle.py
NameError occured

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

Related Topics :

Rahul Kumar

Rahul Kumar

Hi ! My name is Rahul Kumar Rajput. I'm a back end web developer and founder of learnhindituts.com. I live in Uttar Pradesh (UP), India and I love to talk about programming as well as writing technical tutorials and tips that can help to others.

Get connected with me. :) LinkedIn Twitter Instagram Facebook

b2eprogrammers