python in Handling Exceptions try…except try…finally by unitdiploma
•Handling Exceptions
•try…except
•try…finally
Errors and Exceptions
Until now error messages haven’t been more than mentioned, but if you have tried out the examples you have probably seen some. There are (at least) two distinguishable kinds of
Errors: syntax errors and exceptions.
while True print(‘Hello world’)
File “<stdin>”, line 1
while True print(‘Hello world’)
^
SyntaxError: invalid syntax
•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 function 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:
1..>>> 10 * (1/0)
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
ZeroDivisionError: division by zero
2..>>> 4 + spam*3
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
NameError: name ‘spam’ is not defined
3..>>> ‘2’ + 2
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
TypeError: Can’t convert ‘int’ object to str implicitly
Built-in Exceptions
•In Python, all exceptions must be instances of a class that derives from BaseException.
•In a try statement with an except clause that mentions a particular class, that clause also handles any exception classes derived from that class (but not exception classes from which it is derived).
•Two exception classes that are not related via subclassing are never equivalent, even if they have the same name.
•exception Exception
•All built-in, non-system-exiting exceptions are derived from this class. All user-defined exceptions should also be derived from this class.
•exception ArithmeticError
•The base class for those built-in exceptions that are raised for various arithmetic errors: OverflowError, ZeroDivisionError, FloatingPointError.
•exception BufferError
•Raised when a buffer related operation cannot be performed.
•exception LookupError
•The base class for the exceptions that are raised when a key or index used on a mapping or sequence is invalid: IndexError, KeyError. This can be raised directly by codecs.lookup().
Built-in Exceptions Contd…
•Concrete exceptions
•The following exceptions are the exceptions that are usually raised.
•exception AssertionError
•Raised when an assert statement fails.
•exception AttributeError
•Raised when an attribute reference (see Attribute references) or assignment fails. (When an object does not support attribute references or attribute assignments at all, TypeError is raised.)
•exception EOFError
•Raised when the input() function hits an end-of-file condition (EOF) without reading any data. (N.B.: the io.IOBase.read() and io.IOBase.readline() methods return an empty string when they hit EOF.)
•exception FloatingPointError
•Not currently used.
•exception GeneratorExit
•Raised when a generator or coroutine is closed; see generator.close() and coroutine.close(). It directly inherits from BaseException instead of Exception since it is technically not an error.
•exception ImportError
•Raised when the import statement has troubles trying to load a module. Also raised when the “from list” in from … import has a name that cannot be found.
•The name and path attributes can
Handling Exceptions
•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.
while True:
… try:
… x = int(input(“Please enter a number: “))
… break
… except ValueError:
… print(“Oops! That was no valid number. Try again…”)
Handling Exceptions Contd…
•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.
•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.
•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.
Examples
Example 1
for arg in sys.argv[1:]:
try:
f = open(arg, ‘r’)
except OSError:
print(‘cannot open’, arg)
else:
print(arg, ‘has’, len(f.readlines()), ‘lines’)
f.close()
Example 2
def this_fails():
… x = 1/0
…
>>> try:
… this_fails()
… except ZeroDivisionError as err:
… print(‘Handling run-time error:’, err)
…
Handling run-time error: division by zero
Example 3
a = [1, 2, 3]
try:
print “Second element = %d” %(a[1])
# Throws error since there are only 3 elements in array
print “Fourth element = %d” %(a[3])
except IndexError:
print “An error occurred”
User Define Exception
•Programmers may name their own exceptions by creating a new exception class.
•Exceptions need to be derived from the Exception class, either directly or indirectly.
•Although not mandatory, most of the exceptions are named as names that end in “Error” similar to naming of the standard exceptions in python.
Example
#A python program to create user-defined exception
# class MyError is derived from super class Exception
class MyError(Exception):
# Constructor or Initializer
def __init__(self, value):
self.value = value
# __str__ is to print() the value
def __str__(self):
return(repr(self.value))
try:
raise(MyError(3*2))
# Value of Exception is stored in error
except MyError as error:
print(‘A New Exception occured: ‘,error.value
Output (‘A New Exception occured: ‘, 6)