±«Óătv

Error trapping

Error trapping refers to the prediction, finding and fixing of programming errors. Even with the best efforts taken to reduce errors, there will be times when errors are made in a program.

Many programming languages provide error trapping facilities for such situations.

Try, Except, Finally

It is possible for code to raise an exception. The keyword 'Try' can be used to detect possible errors and return a meaningful validation error to the user.

For example:

def errorCheck():
	'''function to catch input errors in python'''
	while True:
		try:
			price = float(input ("Enter Price: "))
		except ValueError:
			print("When I ask for a price, give me a price. Come on!")
		else:
			print('Price accepted')
			return price

The code above uses the 'try' statement to allow the user to enter a price.

Instead of crashing, if the user enters anything other than a number, the program will 'except' the value error and ask them to re-enter a number as the program loops.

The loop will continue until the user enters a number.

Exceptions in programming

Exceptional conditions require special processing.

In general, an exception breaks the normal flow of execution and executes a pre-registered exception . Exceptions and handlers can be used to catch errors at . The pseudocode below shows how this can be achieved.

For example, Order of Operations in programming:

1	try:
2	   	block-1 ...
3	except Exception1:
4	   	handler-1 ...
5	except Exception2:
6	    	handler-2 ...
7	else:
8	    	else-block
9	finally:
10	    	Final-block
  • The code in block-1 is executed (line 2). If the code raises an exception (line 3), the various except blocks are tested (lines 3 - 6).
  • If the exception is of class Exception1, handler-1 is executed (line 4); otherwise, if it's of class Exception2 (line 5), handler-2 is executed (line 6), and so forth. If no exception is raised, the else-block is executed (line 7).
  • No matter what happened previously, the final-block (line 10) is executed once the code is complete and any raised exceptions handled.
  • Even if there's an error in an exception handler or the else-block, the code in the final-block is still run.

Example 1

In this example, the program will first try to divide 100 by the number provided. If the number 0 is entered then, instead of crashing, it will accept the value and run the except block (print("You can't divide by zero")).

Represented in Python:

def divide(num):
	'''function to catch zero division error'''
	try: #exception may occur when running this code
    	print(100/num)
	except ZeroDivisionError: #catch if an error occurs and run this code
		print("You can't divide by zero")
		
if __name__ == "__main__":
	divide(5)
	divide(0)

Will output:

20.0
You can't divide by zero
>>>

Example 2

In this example, the 'finally' clause has been added. Code in the 'finally' block will always be executed. This example shows it running when an error was, and was not, raised. Represented in Python:

def divide(num):
	'''function to catch zero division error'''
	try: #exception may occur when running this code
    	print(100/num)
	except ZeroDivisionError: #catch if an error occurs and run this code
		print("You can't divide by zero")
    finally: #This block of code is executed no matter what happens above
    	print("Your original input was ", num)
		
if __name__ == "__main__":
	divide(5)
	divide(0)

Will output:

20.0
Your original input was 5
You can't divide by zero
Your original input was 0
>>>