try it except in Python

Counters | File handling | Python Methods and Functions

try () is used in handling errors and exceptions
There are two types of errors:

  • Syntax error : Also known as parsing errors, the most basic. Thrown when the Python parser cannot understand a line of code.
  • Exception : Errors encountered during runtime. for example — ZeroDivisionError.

List of exceptional errors:

  • IOError: if the file cannot be opened
  • KeyboardInterrupt: when the user presses an unnecessary key
  • ValueError: when an inline function receives an invalid argument
  • EOFError: if the end of the file is deleted without reading any data
  • ImportError: if the module cannot be found

Now we have the task of handling these errors in our Python code. So here we need to try — except statements.

  Basic Syntax:  try: // Code except: // Code 

How does try () work?

  • The try clause is executed first, i.e. the code between the try clause and the exception .
  • If there are no exceptions, then only the try , clause will be executed, except the clause is completed.
  • If a any exception, the try offer will be skipped and will be executed, except the offer.
  • If any exception occurs, but the exceptions offer in the code does not handle it, it is passed to external try statements. If the exception is not handled, execution stops.
  • The try statement may contain more than one sentence, except for

Code 1: No exceptions, so try will be executed.

# Python code for illustration
# try () work

def divide (x, y):

try :

  # Gender department: gives only fractional part as response

result = x / / y

  print ( "Yeah! Your answer is: " , result)

  except ZeroDivisionError:

  print ( "Sorry! You are dividing by zero" )

 
# Look at the parameters and notice how the program works

divide ( 3 , 2 )

Output:

 ('Yeah! Your answer is:', 1) 

Code 1: Exists exception, so only for the exception clause will work.

# Python code for illustration
# try () work

def divide (x, y):

try :

# Gender department: gives only fractional part as answer

result = x / / y

print ( " Yeah! Your answer is: " , result)

  except ZeroDivisionError:

  print ( "Sorry! You are dividing by zero" )

 
# Look at the parameters and notice how the program works

divide ( 3 , 0 )

Output:

 Sorry! You are dividing by zero 

Related Articles:

Tutorials