dealing with errors. error types syntax errors runtime errors logical errors

19
Dealing with Errors

Upload: reynard-mcgee

Post on 01-Jan-2016

304 views

Category:

Documents


6 download

TRANSCRIPT

Page 1: Dealing with Errors. Error Types Syntax Errors Runtime Errors Logical Errors

Dealing with Errors

Page 2: Dealing with Errors. Error Types Syntax Errors Runtime Errors Logical Errors

Error Types

Syntax Errors Runtime Errors

Logical Errors

Page 3: Dealing with Errors. Error Types Syntax Errors Runtime Errors Logical Errors

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!’)

Page 4: Dealing with Errors. Error Types Syntax Errors Runtime Errors Logical Errors

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+num5Print('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?

Page 5: Dealing with Errors. Error Types Syntax Errors Runtime Errors Logical Errors

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+num5print('The sum is: ', sum)average=(sum/5)print('The average is: ', average)

Page 6: Dealing with Errors. Error Types Syntax Errors Runtime Errors Logical Errors

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)

Page 7: Dealing with Errors. Error Types Syntax Errors Runtime Errors Logical Errors

Syntax or Runtime Error?

print("Here is some text")print(1/0)

Page 8: Dealing with Errors. Error Types Syntax Errors Runtime Errors Logical Errors

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!

Page 9: Dealing with Errors. Error Types Syntax Errors Runtime Errors Logical Errors

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.

Page 10: Dealing with Errors. Error Types Syntax Errors Runtime Errors Logical Errors

Another example of a logical error (forgetting BODMAS!)

Page 11: Dealing with Errors. Error Types Syntax Errors Runtime Errors Logical Errors

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?

Page 12: Dealing with Errors. Error Types Syntax Errors Runtime Errors Logical Errors

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.

Page 13: Dealing with Errors. Error Types Syntax Errors Runtime Errors Logical Errors

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:

Page 14: Dealing with Errors. Error Types Syntax Errors Runtime Errors Logical Errors

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’.

Page 15: Dealing with Errors. Error Types Syntax Errors Runtime Errors Logical Errors

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

Page 16: Dealing with Errors. Error Types Syntax Errors Runtime Errors Logical Errors

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 if python cannot find the module e.g. import unknown_module

A final excample of a common exception error is

the IOError

Page 17: Dealing with Errors. Error Types Syntax Errors Runtime Errors Logical Errors

…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()

Page 18: Dealing with Errors. Error Types Syntax Errors Runtime Errors Logical Errors

…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.

Page 19: Dealing with Errors. Error Types Syntax Errors Runtime Errors Logical Errors

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.