Example: Try and Except

The "try" and "except" commands are the gateway for handling errors. "try" allows you to try to execute your code, and "except" identifies the type of error to be handled. Python contains many built-in exceptions that can be raised using the "except" command. For example, 

  • ValueError: raised if an operation or function receives an argument that has an inappropriate value
  • NameError: raised if a variable name that does not exist is referenced

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--")

Source: Educative, https://www.educative.io/edpresso/how-is-try-except-used-in-python
Creative Commons License This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 License.

Last modified: Tuesday, November 17, 2020, 4:40 PM