cem sahin cs 265 - 002. there are two distinguishable kinds of errors: python's errors syntax...

24
Cem Sahin CS 265 - 002

Upload: simon-davidson

Post on 14-Jan-2016

220 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Cem Sahin CS 265 - 002.  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions

Cem SahinCS 265 - 002

Page 2: Cem Sahin CS 265 - 002.  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions

There are two distinguishable kinds of errors:

Python's Errors

Syntax ErrorsExceptions

Page 3: Cem Sahin CS 265 - 002.  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions

Also known as, parsing errors…You will most likely encounter with

these during the compilation.Example:>>> while True print 'Hello world'

File "<stdin>", line 1, in ? while True print 'Hello world'

^ SyntaxError: invalid syntax

Page 4: Cem Sahin CS 265 - 002.  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions

>>> while True print 'Hello world' File "<stdin>", line 1, in ?

while True print 'Hello world' ^

SyntaxError: invalid syntax If you get an syntax error:

Filename and line number are displayed. The parser repeats the line and places an

arrow (^) right after the token that caused the error.

In this case, a missing semicolon caused the error.

Page 5: Cem Sahin CS 265 - 002.  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions

Exceptions occur during run-time (during execution).

Cause your program to crash!...Some examples are:

ZeroDivisionError NameError TypeError

Unless these are handled, an error message is displayed during execution and the program stops.

Page 6: Cem Sahin CS 265 - 002.  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions

>>> 10 * (1/0) Traceback (most recent call last):

File "<stdin>", line 1, in ? ZeroDivisionError: integer division or modulo

by zero

>>> 4 + spam*3 Traceback (most recent call last):

File "<stdin>", line 1, in ? NameError: name 'spam' is not defined

>>> '2' + 2 Traceback (most recent call last):

File "<stdin>", line 1, in ? TypeError: cannot concatenate 'str' and 'int'

objects

Page 7: Cem Sahin CS 265 - 002.  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions

It is possible to write programs that “takes care” of these exceptions.

Why bother? Because we don’t want our programs to crash…

This is done by using the “try” statement. Try statement works as follows:

First, the try clause is executed. If no exception occurs, the except clause is

skipped. The execution of try statement is done!!

If an exception occurs, the program immediately skips to the except clause.

Page 8: Cem Sahin CS 265 - 002.  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions

>>> def this_fails(): . . . x = 1/0 . . . >>> try: . . . this_fails() . . . except ZeroDivisionError as detail: . . . print 'Handling run-time error:',

detail . . . Handling run-time error: integer division or

modulo by zero

This program does not crash!!!

Page 9: Cem Sahin CS 265 - 002.  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions

The try ... except statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception.

This actually can be done in a different way too… (coming soon)

Page 10: Cem Sahin CS 265 - 002.  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions

for arg in sys.argv[1:]: try:

f = open(arg, 'r') except IOError:

print 'cannot open', arg else:

print arg, 'has', len(f.readlines()), ‘lines’

f.close()

Page 11: Cem Sahin CS 265 - 002.  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions

The “raise” statement allows the programmer to force a specified exception to occur.

Why do we want to do this? For “programmer defined” exceptions To test your code…

>>> raise NameError('HiThere') Traceback (most recent call last):

File "<stdin>", line 1, in ? NameError: HiThere

Page 12: Cem Sahin CS 265 - 002.  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions

The argument to raise is an exception class or an instance to be raised.

>>> try: . . . raise NameError('HiThere') . . . except NameError: . . . print 'An exception flew by!' . . . raise . . . An exception flew by! Traceback (most recent call last):

File "<stdin>", line 2, in ? NameError: HiThere

Page 13: Cem Sahin CS 265 - 002.  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions

If an exception occurs, a message will be printed, as shown in the previous slides, ONLY IF it is a built-in exception.

If we’re expecting to get a different type of exception, we need to define it in our program. Example: For the GADS files,

FlightNotFoundException can be defined…

Page 14: Cem Sahin CS 265 - 002.  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions

Programmers can define their own exceptions by creating a new exception class.

Exceptions should be derived from the Exceptions class, either directly or indirectly.

>>> class MyError(Exception): . . . def __init__(self, value): . . . self.value = value . . . def __str__(self): . . . return repr(self.value) . . . >>> try: . . . raise MyError(2*2) . . . except MyError as e: . . . print 'My exception occurred, value:',

e.value . . . My exception occurred, value: 4

Page 15: Cem Sahin CS 265 - 002.  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions

How do we know that it is a user defined exception?

>>> raise MyError('oops!') Traceback (most recent call last):

File "<stdin>", line 1, in ? __main__.MyError: ‘oops!’

It prints the name that we defined when we raise it.

Page 16: Cem Sahin CS 265 - 002.  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions

An exception causes the try statement to stop executing, which may cause some problems for the rest of the program (and most of the time, it does).

Example: Close files that are left open. Release any resources allocated during the

run. This is done by adding a “finally” clause

after the try…except block..

Page 17: Cem Sahin CS 265 - 002.  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions

>>> def divide(x, y): . . . try: . . . result = x / y . . . except ZeroDivisionError: . . . print "division by zero!" . . . else: . . . print "result is", result . . . finally: . . . print "executing finally

clause" . . .

Page 18: Cem Sahin CS 265 - 002.  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions

>>> divide(2, 1) result is 2 executing finally clause

>>> divide(2, 0) division by zero! executing finally clause

>>> divide("2", "1") executing finally clause Traceback (most recent call last):

File "<stdin>", line 1, in ? File "<stdin>", line 3, in divide

TypeError: unsupported operand type(s) for /: 'str' and 'str'

Page 19: Cem Sahin CS 265 - 002.  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions

Try clause

Else clause

Except clause

Finally clause

Is there an else clause?

No

Yes

Exception occurs No exception occurs

Rest of the code

Page 20: Cem Sahin CS 265 - 002.  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions

PYTHON

try:……..

except ZeroDivisionError as e:print “Error:”, e.value

else:……..

finally:……..

raise MyError(4)

JAVA

try{……… }

catch(ZeroDivisionException e){System.out.println(“Error” + e.getMessage());

}finally{

……… }

throw new MyError(4);

Page 21: Cem Sahin CS 265 - 002.  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions

Some objects define standard clean-up actions to be taken when the object is no longer needed.

for line in open("myfile.txt"): print line

Prints each line in myfile.txtProblem with this code?

It leaves the file open…

Page 22: Cem Sahin CS 265 - 002.  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions

How to fix it? The with statement allows objects like files to

be used in a way that ensures they are always cleaned up promptly and correctly.

with open("myfile.txt") as f: for line in f:

print line

After each with statement is executed, the file f is closed.

How can we know about these predefined actions? They are defined in each objects

documentation.

Page 23: Cem Sahin CS 265 - 002.  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions

To raise an exception, or not:

That is the question!…

Page 24: Cem Sahin CS 265 - 002.  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions

“8. Errors and Exceptions – Python v.2.6.4 documentation”. Python Software Foundation. 22 November 2009. <http://docs.python.org/tutorial/errors.html>

Horstman, Cay. Big Java: Third Edition. John Wiley & Sons, Inc. 2008.