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 ! 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