Presentation is loading. Please wait.

Presentation is loading. Please wait.

Dealing with Errors. Error Types Syntax Errors Runtime Errors Logical Errors.

Similar presentations


Presentation on theme: "Dealing with Errors. Error Types Syntax Errors Runtime Errors Logical Errors."— Presentation transcript:

1 Dealing with Errors

2 Error Types Syntax Errors Runtime Errors Logical Errors

3 Syntax Error Where the programmer enters something that breaks the rule of the language… or…uses a token (letter, symbol or operator) that is not defined in the grammar of the language. >>> if a > b >>> print(‘A is greater than B!’) A syntax error has occurred! >>> if a > b : >>> print(‘A is greater than B!’)

4 Syntax Error num1 = int(input('What is your first number? ')) num2 = int(input('What is your second number? ')) num3 = int(input('What is your third number? ')) num4 = int(input('What is your fourth number? ')) num5 = int(input('What is your fifth number? ')) sum = num1+num2+num3+num4+num5 Print('The sum is: ' sum) Average:(sum/5) pint('The average is: ', average)) Syntax errors are quite easy to spot and fix. The compiler debugger (and an interpreter) will raise this error when it notices that a syntax error has occurred. How many syntax errors can you spot below?

5 Syntax Error How many syntax errors can you spot below? 5 Syntax Errors! num1 = int(input('What is your first number? ')) num2 = int(input('What is your second number? ')) num3 = int(input('What is your third number? ')) num4 = int(input('What is your fourth number? ')) num5 = int(input('What is your fifth number? ')) sum = num1+num2+num3+num4+num5 print('The sum is: ', sum) average=(sum/5) print('The average is: ', average)

6 Runtime Error These errors occur whenever the program instructs the computer to carry out an operation that it is not designed to do or very slow to do. One of the most common runtime errors is when a program instructs a computer to divide any number by the value zero >>> print(1/0) This operation produces an infinitely large result, which is too large for a computer to accommodate. Here is another runtime error – adding a string and a number. >>> print("you cannot add text and numbers" + 12)

7 Syntax or Runtime Error? print("Here is some text") print(1/0)

8 Syntax or Runtime Error? print("Here is some text") print(1*0 Remember, a program with a syntax error will execute NO steps at all!

9 Logical Error These types of errors are regarded as the most difficult to spot. Similar to the runtime error, the interpreter will not give you any message or warning and the program will run perfectly fine without hanging. However, the program will not behave in the manner it was designed to. In other words, it will simply produce incorrect results. if score > 50: print(‘C’) elif score >75: print(‘B’) elif score >85: print(‘A’) Anna scores 80 in her test, however, when she puts her score into the program, it displays a ‘C’ grade…and not the expected ‘B’ grade.

10 Another example of a logical error (forgetting BODMAS!)

11 It is impossible to foresee all situations in which errors occur in a program. As we anticipate these problematic situations, many programming languages provide error handling techniques. X = int(input(‘Please enter your first number’)) Y = int(input(‘Please enter your second number’)) print(X/Y) Error Catching If the user typed in 0 for their second number, we would get a Runtime error! How do we get around this situation?

12 The solution is to try to ‘catch’ the error.. try: X = int(input(‘Please enter your first number’)) Y = int(input(‘Please enter your second number’)) print(X/Y) Error Catching The word ‘ try: ’ instructs the compiler/interpreter to execute the block of code as normal. It will attempt to execute the code in here first of all.

13 try: X = int(input(‘Please enter your first number’)) Y = int(input(‘Please enter your second number’)) print(X/Y) Error Catching If there happens to be an error here somewhere (e.g. the end user types in 0 for Y…a runtime error) …the program would normally crash/terminate! We can avoid this by using except:

14 try: X = int(input(‘Please enter your first number’)) Y = int(input(‘Please enter your second number’)) print(X/Y) except ZeroDivisionError: print(‘You cannot divide by zero!’) Y=1 Error Catching Try this for yourself and see if it works. Note: this category of error exception ‘ ZeroDivisionError ’.

15 Another exception error worth noting is the ValueError Value Errors: int(‘T’) For when the arguments of a function have invalid values! Solution: try: x=int(input(‘Please enter a number: ‘)) except ValueError: print(‘Invalid entry, please try again’)

16 try: test_file = open(‘crazy_file_name.txt’,’r’) Text_file.write(‘Hey there!’) except IOError: print(‘This file doesn’t exist!’) test_file.close() the ‘ IOError ’ is when no file exists or can’t be opened. the ImportError i f python cannot find the module e.g. import unknown_module A final excample of a common exception error is the IOError

17 …finally: Look at the code below. If the file ‘ CrazyFile.txt ’ does not exist, then the IOError exception error will be raised and the except clause will handle the situation and close the file. What if there is no exception error? The file will remain open which is not good for our program. try: my_file = open(‘CrazyFile.txt’, ‘r’) print(my_file.read()) except IOError: print(‘no such file exists!’) my_file.close()

18 …finally: It turns out that the ‘ try…finally ’ can help solve this situation. try: my_file = open(‘CrazyFile.txt’, ‘r’) try: print(my_file.read()) finally : my_file.close() except IOError: print(‘no such file exists!’) Note: the finally block will be executed regardless of any exception Once the file has been opened successfully by the open function, you want to make absolutely sure that you close it, even if an exception is raised by the seek or read methods. That's what a try...finally block is for: code in the finally block will always be executed, even if something in the try block raises an exception. Think of it as code that gets executed on the way out, regardless of what happened before.

19 Task 1.Create a program that opens an external text file called animals.txt 2.The contents of this file should be output on the screen. 3.Handle any IOErrors that could potentially occur here. 4.If the user wants to add a new animal, they should type in a number (e.g. 1) Amend your program to allow for this. 5.Refine your program further so that it does not encounter a runtime error if the user enters a letter instead of a number. 6.Your program should then invite the end user to add more animals. These new animals should be added accordingly to the text file, with each new animal on a separate line.


Download ppt "Dealing with Errors. Error Types Syntax Errors Runtime Errors Logical Errors."

Similar presentations


Ads by Google