Difference between revisions of "Exceptions in Python"

From Sustainability Methods
m (This article provides an introduction to the different kinds of exceptions and how to handle them)
(No difference)

Revision as of 05:24, 30 June 2023

THIS ARTICLE IS STILL IN EDITING MODE

Exception- good to know

An Exception is an error when you execute your code. When a code tried to do something and fail, without proper “exception handling” it will stop and won’t continue its next line.

Example

Run the code below to see different types of exception

1/0

You will get "ZeroDivisionError" when you try to divide a number by 0.

y = x + 1
# or
y = new_function()

You will get "NameError" if you try to use a variable that has not been defined before.

a = [1,2,3,4,5]
a[10]

You will get "IndexError" when you try to call an array with an index larger than the array itself.

There are many more exceptions, which you can find by searching for “python exception documentation” on the internet.

Exception Handling

As discussed before, exceptions can be handled better. By using “try - except” block, we can manually avert the error. A basic Try-Except Example will look like this:

# other code running perfectly fine

try:
	# code that can go wrong
except: 
	# code to execute when "try" block is triggered

# code will still continue when there is an exception

Let's look at Try-Exception in action

a = 1
try: 
	b = int(input("a number to divide a")) # insert here for example 5 or 0
	a = a / b
	print("Success, a = ", a)

except: 
	print("There was an error")

Try using 0 and other input as input to see if you get a success or not.

There is a way to differentiate reactions based on the exception type. For example, if you want to print different error codes for each of the exceptions. Well, you can!

a = 1
z=(4,2,9,6)
#y=1
try: 
	b = int(input(0))
	a = (a / b)*y-z[2]
	print(a)
except ZeroDivisionError:
    a= (a / 1)*1-z[2]
    print("Zero Division Error, check your code for division by 0, 0 replaced by one, y replaced by 1. a= ", a)
except NameError:
    a= (a / b)*1-z[2]
    print("Name Error, check the variable / function name of your code, y replaced by one, a= ", a)
except IndexError:
    a= (a / b)*1-1
    print("Index Error, check the array again, z[7] replaced by 1, a= ", a)

Run the code so that no zero division error occurs. What do you see? What do you see if you take b=0? You can also play a little with the different errors that occur: What do you see if you take z[9], define y, and b=2?

Quiz

  1. Open the search engine of your choice and look for other exceptions. Pick one and try to add it to the last code in this tutorial
  2. Modify the code so that it runs until the end (and add descriptions of exceptions where needed):
z=[0,4,6,3,34439,404]
x= 5/z[0]
a= (x-z[8])**2

The author of this entry is XX. Edited by Milan Maushart