week 14 - 15 exception handling. syntax errors syntax errors, also known as parsing errors, are...

34
WEEK 14 - 15 EXCEPTION HANDLING

Upload: neal-jackson

Post on 27-Dec-2015

228 views

Category:

Documents


0 download

TRANSCRIPT

WEEK 14 - 15

EXCEPTION HANDLING

Syntax Errors

• Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while you are still learning Python:

• >>> while True print 'Hello world' • File "<stdin>", line 1, in ? • while True print 'Hello world' • ^ • SyntaxError: invalid syntax

Syntax Errors

• The parser repeats the offending line and displays a little ‘arrow’ pointing at the earliest point in the line where the error was detected.

• The error is caused by (or at least detected at) the token preceding the arrow: in the example, the error is detected at the keyword print, since a colon (':') is missing before it.

• File name and line number are printed so you know where to look in case the input came from a script.

Exceptions

• Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it.

• Errors detected during execution are called exceptions and are not unconditionally fatal: you will soon learn how to handle them in Python programs.

• Most exceptions are not handled by programs, however, and result in error messages as shown here:

Examples• >>> 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

Examples

• The last line of the error message indicates what happened.

• Exceptions come in different types, and the type is printed as part of the message: the types in the example are ZeroDivisionError, NameError and TypeError.

Examples

• The string printed as the exception type is the name of the built-in exception that occurred.

• This is true for all built-in exceptions, but need not be true for user-defined exceptions (although it is a useful convention).

• Standard exception names are built-in identifiers (not reserved keywords).

cont

• The rest of the line provides detail based on the type of exception and what caused it.

• The preceding part of the error message shows the context where the exception happened, in the form of a stack traceback.

• In general it contains a stack traceback listing source lines; however, it will not display lines read from standard input.

Exceptions Handling

• It is possible to write programs that handle selected exceptions.

• Look at the following example, which asks the user for input until a valid integer has been entered, but allows the user to interrupt the program (using Control-C or whatever the operating system supports); note that a user-generated interruption is signalled by raising the KeyboardInterrupt exception.

Example

• while True: • try: • x = int(raw_input("Please enter a• number: ")) • break • except ValueError: • print "Oops! That was no valid number.• Try again..."

Example Explained

• The try statement works as follows.• First, the try clause (the statement(s) between

the try and except keywords) is executed.• If no exception occurs, the except clause is

skipped and execution of the try statement is finished.

explained

• If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try statement.

explained

• If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops with a message as shown above.

explained

• A try statement may have more than one except clause, to specify handlers for different exceptions. At most one handler will be executed. Handlers only handle exceptions that occur in the corresponding try clause, not in other handlers of the same try statement. An except clause may name multiple exceptions as a parenthesized tuple, for example:

explained

• except (RuntimeError, TypeError, NameError):• pass

cont

• Note that the parentheses around this tuple are required, because except ValueError, e: was the syntax used for what is normally written as except ValueError as e: in modern Python (described below).

• The old syntax is still supported for backwards compatibility. This means except RuntimeError, TypeError is not equivalent to except (RuntimeError, TypeError): but to except RuntimeError as TypeError: which is not what you want.

What is Exception?

• An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.

• In general, when a Python script encounters a situation that it can't cope with, it raises an exception.

• An exception is a Python object that represents an error.

cont

• When a Python script raises an exception, it must either handle the exception immediately otherwise it would terminate and come out.

Handling an exception

• If you have some suspicious code that may raise an exception, you can defend your program by placing the suspicious code in a try: block.

• After the try: block, include an except: statement, followed by a block of code which handles the problem as elegantly as possible.

Syntax

• Here is simple syntax of try....except...else blocks:

Syntax

• try:• You do your operations here;• ......................• except ExceptionI:• If there is ExceptionI, then execute this block.• except ExceptionII:• If there is ExceptionII, then execute this block.• ……….......................• else: If there is no exception then execute this• block.

Syntax explained

• Here are few important points about the above-mentioned syntax:

• A single try statement can have multiple except statements. This is useful when the try block contains statements that may throw different types of exceptions.

• You can also provide a generic except clause, which handles any exception.

• After the except clause(s), you can include an else-clause. The code in the else-block executes if the code in the try: block does not raise an exception.

• The else-block is a good place for code that does not need the try: block's protection.

Examples

• Here is simple example, which opens a file and writes the content in the file and comes out gracefully because there is no problem at all:

cont

• #!/usr/bin/python• try:• fh = open("testfile", "w")• fh.write("This is my test file for exception• handling!!")• except IOError:• print "Error: can\'t find file or read data“• else:• print "Written content in the file successfully"

fh.close()

cont

• This will produce the following result:• Written content in the file successfully

• Here is one more simple example, which tries to open a file where you do not have permission to write in the file, so it raises an exception:

Example

• #!/usr/bin/python• try:• fh = open("testfile", "w")• fh.write("This is my test file for exception• handling!!")• except IOError:• print "Error: can\'t find file or read data“• else: print "Written content in the file • successfully"

cont

• This will produce the following result:• Error: can't find file or read data

The except clause with no exceptions:

• You can also use the except statement with no exceptions defined as follows:

• try:• You do your operations here;• ...................... • except:• If there is any exception, then execute this block.• ...................... • else:• If there is no exception then execute this block.

cont

• This kind of a try-except statement catches all the exceptions that occur.

• Using this kind of try-except statement is not considered a good programming practice though, because it catches all exceptions but does not make the programmer identify the root cause of the problem that may occur.

The except clause with multiple exceptions:

• You can also use the same except statement to handle multiple exceptions as follows:

• try:• You do your operations here;• ...................... • except(Exception1[, Exception2[,...ExceptionN]]]):• If there is any exception from the given exception list,• then execute this block.• ...................... • else:• If there is no exception then execute this block.

The try-finally clause:

• You can use a finally: block along with a try: block. The finally block is a place to put any code that must execute, whether the try-block raised an exception or not.

• The syntax of the try-finally statement is this:

cont

• try:• You do your operations here;• ......................• Due to any exception, this may be skipped. finally:• This would always be executed.• ......................• Note that you can provide except clause(s), or a

finally clause, but not both. You can not use else clause as well along with a finally clause.

Example

• #!/usr/bin/python• try:• fh = open("testfile", "w")• fh.write("This is my test file for exception

handling!!") • finally:• print "Error: can\'t find file or read data"

cont

• If you do not have permission to open the file in writing mode, then this will produce the following result:

• Error: can't find file or read data