Exception Handling

Exception handling:

  • We don't want to scare the user away

  • We don't want the user to see log like stack traces when errors are shown

  • That's where exception handling comes in

Raw code before exception handling:

def sum(num1, num2):
	print(num1+num2)
	
number1 = input("Enter a number: ")

sum(number1, 12)
  • Will generate a type error as the input function converts anything you give it to string

  • Any code other than 0 generates an error

  • Error:

Traceback (most recent call last):
  File "c:\Users\$USERNAME\Desktop\test.py", line 6, in <module>
    sum(number1, 12)
  File "c:\Users\$USERNAME\Desktop\test.py", line 2, in sum     
    print(num1+num2)
TypeError: can only concatenate str (not "int") to str
  • By handling exceptions, you don't display the above stack to the user

Code after exception handling:

  • To handle the errors there is a special syntax called try and except

def sum(num1, num2):
	try:
		print(num1+num2)
	except:
		print("There was an error")
		
print('HELLO')
	
number1 = input("Enter a number: ")

sum(number1, 12)
  • By handling the Exception, the rest of the code in the grand scope will run

    • Such as print('HELLO')

    • This is due to scope

  • The exception will be handled gracefully and will not crash the rest of the program

Exception handling should be used only if you don't have any control over how it is used

  • Example:

    • The software goes to the internet and downloads files, and the user runs your program with no internet access, that could cause a crash

    • Another example is if the program relies on a file to be on the file system. If that is not there it will crash

The above code does not need any exception handling really, as the data type is in our control

def sum(num1, num2):
	if isinstance(num1, int) and isinstance(num2, int):
		print(num1+num2)
	else:
		print('Please enter numbers only')
		
number1 = input("Enter a number: ")
sum(number1, 12)
  • isinstance checks for data types specified

Last updated