Python except కీలకపదం

ఉదాహరణ

ఉంటే సూత్రం దోషం ప్రారంభిస్తుంది అప్పుడు "ఏదో దోషం వచ్చింది" ప్రింట్ చేయండి:

try:
  x > 3
except:
  print("ఏదో దోషం వచ్చింది")

ఇన్స్టాన్స్ నడుపు

నిర్వచనం మరియు వినియోగం

try ... except బ్లాక్లో except కీలకపదాన్ని వాడబడింది. ఇది try బ్లాక్ విఫలం కావడంతో పనిచేసే కోడ్ బ్లాక్ని నిర్వచిస్తుంది.

మీరు వివిధ దోషపురుగుల కొరకు వేరే బ్లాక్లను నిర్వచించవచ్చు, మరియు సమస్య లేకుండా పనిచేసే బ్లాక్లను, క్రింది ఉదాహరణను చూడండి.

More instances

ఇన్స్టాన్స్ 1

If NameError is raised, write a message, and if TypeError is raised, write another message:

x = "hello"
try:
  x > 3
except NameError:
  print("You have a variable that is not defined.")
except TypeError:
  print("You are comparing values of different type")

ఇన్స్టాన్స్ నడుపు

ఇన్స్టాన్స్ 2

Attempt to execute a statement that raises an error, but do not define the error type (in this case ZeroDivisionError):

try:
  x = 1/0
except NameError:
  print("You have a variable that is not defined.")
except TypeError:
  print("You are comparing values of different type")
except:
  print("Something else went wrong")

ఇన్స్టాన్స్ నడుపు

ఇన్స్టాన్స్ 3

If no error occurs, write a message:

x = 1
try:
  x > 10
except NameError:
  print("You have a variable that is not defined.")
except TypeError:
  print("You are comparing values of different type")
else:
  print("The 'Try' code was executed without raising any errors!")

ఇన్స్టాన్స్ నడుపు

సంబంధిత పేజీలు

try కీవర్డ్

finally కీవర్డ్