How is try/except used in Python?

Exception handling

An exception is an error that occurs while the program is executing

When this error occurs, the program will stop and generate an exception which then gets handled in order to prevent the program from crashing.

Try/except

The exceptions generated by a program are caught in the try block and handled in the except block.

  • Try: Lets you test a block of code for errors.

  • Except: Lets you handle the error.

Examples

Let’s take a look at a simple example of try/except.

try:
print (x)
except:
print ("An error occurred")

Since x is not defined anywhere in the code, an exception will occur hence the except block will execute and display the message.

You can define as many exception blocks as you want for different errors as shown below.

try:
print (x)
except ValueError: #you'll get this error if there is a problem with the content of the object you tried to assign the value to
print ("Non-numeric data found")
except NameError: #you'll get this error if program encounters a name that it doesn't recognize
print ("Variable x is not defined")
except:
print ("Some error occured")

You can also used the else keyword to define code that should be executed if no errors are raised.

try:
print ("Hello World")
except ValueError:
print ("Non-numeric data found")
except NameError:
print ("Variable x is not defined")
except:
print ("Some error occured")
else:
print ("Nothing went wrong")

You can also use finally keyword that will be executed, no matter if there is an error or not.

try:
print ("Hello World")
except ValueError:
print ("Non-numeric data found")
except NameError:
print ("Variable x is not defined")
except:
print ("Some error occured")
finally:
print ("--Finally--")
Copyright ©2024 Educative, Inc. All rights reserved