Cem Sahin CS
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 " ", line 1, in ? while True print 'Hello world' ^ SyntaxError: invalid syntax
>>> while True print 'Hello world' File " ", 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.
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.
>>> 10 * (1/0) Traceback (most recent call last): File " ", line 1, in ? ZeroDivisionError: integer division or modulo by zero >>> 4 + spam*3 Traceback (most recent call last): File " ", line 1, in ? NameError: name 'spam' is not defined >>> '2' + 2 Traceback (most recent call last): File " ", line 1, in ? TypeError: cannot concatenate 'str' and 'int' objects
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.
>>> 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!!!
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)
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()
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 " ", line 1, in ? NameError: HiThere
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 " ", line 2, in ? NameError: HiThere
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…
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
How do we know that it is a user defined exception? >>> raise MyError('oops!') Traceback (most recent call last): File " ", line 1, in ? __main__.MyError: ‘oops!’ It prints the name that we defined when we raise it.
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..
>>> def divide(x, y):... try:... result = x / y... except ZeroDivisionError:... print "division by zero!"... else:... print "result is", result... finally:... print "executing finally clause"...
>>> 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 " ", line 1, in ? File " ", line 3, in divide TypeError: unsupported operand type(s) for /: 'str' and 'str'
Try clause Else clause Except clause Finally clause Is there an else clause? No Yes Exception occursNo exception occurs Rest of the code
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);
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.txt Problem with this code? It leaves the file open…
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.
To raise an exception, or not: That is the question!…
“8. Errors and Exceptions – Python v documentation”. Python Software Foundation. 22 November Horstman, Cay. Big Java: Third Edition. John Wiley & Sons, Inc