The document discusses exception handling in Python programs. It explains that exceptions are unexpected errors that occur during program execution. It provides examples of common error types and describes how to raise exceptions using raise statements. It also explains how to handle exceptions using try-except blocks, which allow catching specific exception types or all exceptions. Finally, it provides some example code demonstrating raising and handling exceptions when working with files and other Python code.
Download as PPTX, PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
18 views
Exception Handling
The document discusses exception handling in Python programs. It explains that exceptions are unexpected errors that occur during program execution. It provides examples of common error types and describes how to raise exceptions using raise statements. It also explains how to handle exceptions using try-except blocks, which allow catching specific exception types or all exceptions. Finally, it provides some example code demonstrating raising and handling exceptions when working with files and other Python code.
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 13
Exception Handling
programs have to deal with errors. Here errors are not
syntax errors instead they are the unexpected condition(s) that are not part of normal operations planned during coding. Partial list of such kinds of errors are: Out of Memory Invalid filename Attempting to write into read only file Getting an incorrect input from user Division by zero Accessing an out of bound list element Trying to read beyond end of file Sending illegal arguments to a method if an error happens, there must be code written in program, to recover from the error. In case if it is not possible to handle the error then it must be reported in user friendly way to the user.
Errors are exceptional, unusual and unexpected
situations and they are never part of the normal flow of a program. when an exception occurs in the program, we say that exception was raised or thrown. Next, we deal with it and say it is handled or caught. And the code written to handle it is known as exception handler. For handling exceptional situations python provides 1. raise statement to raise exception in program 2. try..... except statement for catching and handling the errors. Raise statement allows the programmer to force a specified exception to occur. Once an exception is raised, it's up to caller function to either handle it using try/except statement or let it propagate further. Syntax of raise is: raise [exception name [, argument]] A raise statement that does not include an exception name will simply re raise the current exception. Here exception name is the type of error, which can be string, class or object and argument is the value. As argument is optional its default value None is used in case the argument is not provided. Python has got some predefined error types, which we can use with raise statement. This does not mean that raise can't be used to raise user defined errors. Example: l = [1,2,3] i=5 if i > len(l): raise IndexError else: print l[i] As the value assigned to i is 5, the code will raise an error, during execution. The error will be index error as mentioned in raise statement. In order to handle the errors raised by the statement, we can use try except statement. try.....except is used when we think that the code might fail. If this happens then we are able to catch it and handle same in proper fashion. While true: try: x = int(raw_input("Enter a number")) break except ValueError: print " This was not a valid number. Enter a valid number" This code will ask user to input a value until a valid integer value is entered. Once while loop is entered execution of try clause begins, if no error is encountered, i.e. the value entered is integer, except clause will be skipped and execution of try finishes. If an exception occurs i.e. an integer value is not entered then rest of try clause is skipped and except cause is executed. try: statements which might go wrong except error type1: statements to be executed, if error type1 happens [except error type2: statements to be executed, if error type 2 happens else: statements to be executed, if no exception occurs finally: statements to be executed]
Remember error type can be user defined also.
You can see a single try statement can have multiple except statements. This is required to handle more than one type of errors in the piece of code. In multiple except clauses, a search for except is taken up. Once a match is found it is executed. You may not specify an error type in exception clause. If that is done, it is to catch all exceptions. Such exceptions should be listed as last clause in the try block. The else clause written after all except statements, is executed, if code in try block does not raise any exception. finally clause is always executed before leaving the try statement irrespective of occurrence of exception. It is also executed if during execution of try and except statement any of the clause is left via break, continueor return statement. Example programs try: x=y except: print " y not defined " Example code having except, else and finally clause def divide(x, y): try: result = x / y except ZeroDivisionError: print "division by zero!“ else: print "result is", result finally: print "executing finally clause" Let's apply exception handling in data file. 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" This will produce the following result, if you are not allowed to write in the file Error: can't find file or read data Another example of error handling in data file: lists = [ ] infile = open('yourfilename.pickle', 'r') while 1: try: lists.append(pickle.load(infile)) except EOFError: break infile.close() This will allow us to read data from a file containing many lists, a list at a time.