20
Chapter 24 Chapter 24 Exception Exception CSC1310 Fall 2009 CSC1310 Fall 2009

Chapter 24 Exception CSC1310 Fall 2009. Exceptions Exceptions Exceptions are events that can modify the flow or control through a program. They are automatically

Embed Size (px)

Citation preview

Page 1: Chapter 24 Exception CSC1310 Fall 2009. Exceptions Exceptions Exceptions are events that can modify the flow or control through a program. They are automatically

Chapter 24Chapter 24ExceptionException

CSC1310 Fall 2009CSC1310 Fall 2009

Page 2: Chapter 24 Exception CSC1310 Fall 2009. Exceptions Exceptions Exceptions are events that can modify the flow or control through a program. They are automatically

ExceptionsExceptions Exceptions Exceptions are events that can modify the flow or

control through a program. They are automatically triggered on errors. try/excepttry/except : catch and recover from raised by you or

Python exceptions try/finallytry/finally: perform cleanup actions whether

exceptions occur or not raiseraise: trigger an exception manually in your code assertassert: conditionally trigger an exception in your

code

Page 3: Chapter 24 Exception CSC1310 Fall 2009. Exceptions Exceptions Exceptions are events that can modify the flow or control through a program. They are automatically

Exception RolesException Roles Error handlingError handling

Wherever Python detects an error it raises exceptions Default behavior: stops program. Otherwise, code try to catch and recover from the

exception (try handler) Event notificationEvent notification

Can signal a valid condition (for example, in search) Special-case handlingSpecial-case handling

Handles unusual situations Termination actionsTermination actions

Guarantees the required closing-time operators (try/finally) Unusual control-flowsUnusual control-flows

A sort of high-level “goto”

Page 4: Chapter 24 Exception CSC1310 Fall 2009. Exceptions Exceptions Exceptions are events that can modify the flow or control through a program. They are automatically

ExampleExample

Page 5: Chapter 24 Exception CSC1310 Fall 2009. Exceptions Exceptions Exceptions are events that can modify the flow or control through a program. They are automatically

try/except/elsetry/except/else

try: <block of statements> #main code to runexcept <name1>: #handler for exception <block of statements>except <name2>,<data>: #handler for exception <block of statements>except (<name3>,<name4>): #handler for exception <block of statements>except: #handler for exception <block of statements>else: # optional, runs if no exception occurs

<block of statements>

Page 6: Chapter 24 Exception CSC1310 Fall 2009. Exceptions Exceptions Exceptions are events that can modify the flow or control through a program. They are automatically

ExampleExample

>>>try: action() except NameError(): … except IndexError(): … except KeyError(): … except (AttributeError,TypeError,SyntaxError):… else: …. General catch-all clause: add empty except. It may catch unrelated to your code system

exceptions. It may catch exceptions meant for other handler

(system exit)

Page 7: Chapter 24 Exception CSC1310 Fall 2009. Exceptions Exceptions Exceptions are events that can modify the flow or control through a program. They are automatically

try/elsetry/else elseelse is used to verify if no exception occurred

in trytry. You can always eliminate elseelse by moving its

logic at the end of the trytry block. However, if “else statement” triggers

exceptions, it would be misclassified as exception in try block.

Page 8: Chapter 24 Exception CSC1310 Fall 2009. Exceptions Exceptions Exceptions are events that can modify the flow or control through a program. They are automatically

try/finallytry/finally

In try/finallytry/finally, finallyfinally block is always run whether an exception occurs or not

try: <block of statements>finally: <block of statements>

Ensure some actions to be done in any case It can not be used in the trytry with exceptexcept and elseelse.

Page 9: Chapter 24 Exception CSC1310 Fall 2009. Exceptions Exceptions Exceptions are events that can modify the flow or control through a program. They are automatically

ExamplesExamples

Page 10: Chapter 24 Exception CSC1310 Fall 2009. Exceptions Exceptions Exceptions are events that can modify the flow or control through a program. They are automatically

raiseraise raiseraise triggers exceptions explicitlyraise <name>raise <name>,<data> # provide data to handlerraise #re-raise last exception

>>>try: raise ‘zero’, (3,0) except ‘zero’: print “zero argument” except ‘zero’, data: print data

Last form may be useful if you want to propagate cought exception to another handler.

Exception name: built-in name, string, user-defined class

Page 11: Chapter 24 Exception CSC1310 Fall 2009. Exceptions Exceptions Exceptions are events that can modify the flow or control through a program. They are automatically

ExampleExample

Page 12: Chapter 24 Exception CSC1310 Fall 2009. Exceptions Exceptions Exceptions are events that can modify the flow or control through a program. They are automatically

assertassert assertassert is a conditional raiseraiseassert <test>, <data>assert <test> If <test> evaluates to false, Python raises

AssertionError with the <data> as the exception’s extra data.

Page 13: Chapter 24 Exception CSC1310 Fall 2009. Exceptions Exceptions Exceptions are events that can modify the flow or control through a program. They are automatically

Exception ObjectsException Objects String-based exceptionsString-based exceptions are any string object

Class-based exceptionsClass-based exceptions are identified with classes. They also identify categories of exceptions.

String exceptions are matched by object identityobject identity: isis Class exceptions are matched by superclass identitysuperclass identity: exceptexcept catches

instances of the mentioned class and instances of all its subclasses lower in the class tree.

Page 14: Chapter 24 Exception CSC1310 Fall 2009. Exceptions Exceptions Exceptions are events that can modify the flow or control through a program. They are automatically

Class Exception ExampleClass Exception Example>>>class General: pass>>>class Specific1(General): pass>>>class Specific2(General): pass>>>def raiser0(): X = General() # raise superclass instance raise X>>>def raiser1(): raise Specific1 # raise subclass instance>>>def raiser2(): X = Specific2() # raise different subclass instance raise X>>>for func in (raiser0, raiser1, raiser2): try: func() except General: import sys; print 'caught:', sys.exc_type

Page 15: Chapter 24 Exception CSC1310 Fall 2009. Exceptions Exceptions Exceptions are events that can modify the flow or control through a program. They are automatically

Built-in Exception ClassesBuilt-in Exception Classes

ExceptionException – top-level root superclass of exceptions. StandardErrorStandardError – the superclass of all built-in error

exceptions. ArithmeticError – the superclass of all numeric errors. OverflowErrorOverflowError – a subclass that identifies a specific

numeric error.

>>>import exceptions>>>help(exceptions)

Page 16: Chapter 24 Exception CSC1310 Fall 2009. Exceptions Exceptions Exceptions are events that can modify the flow or control through a program. They are automatically

Nesting Exception Nesting Exception HandlersHandlers

Once the exception is caught, it’s life is over.

finallyfinally does not kill exception – just specify code to be run on the way out.

Page 17: Chapter 24 Exception CSC1310 Fall 2009. Exceptions Exceptions Exceptions are events that can modify the flow or control through a program. They are automatically

Exception IdiomsException Idioms All errors are exceptions, but not all exceptions are errors. It could be

signals or warnings (warnings module)>>>while True: try: line=raw_input() except EOFError: break else: # process next line Functions signal conditions with raiseraise (to distinguish success or failure) Debugging with outer trytry statementtry: … # run programexcept: import sys; print sys.exc_type,sys.exc_value

Page 18: Chapter 24 Exception CSC1310 Fall 2009. Exceptions Exceptions Exceptions are events that can modify the flow or control through a program. They are automatically

Exception Design TipsException Design Tips Operations that commonly fail are generally wrapped in try statements(file opens, socket calls).

However, you may want failures of such operations to kill your program instead of being caught and ignored if the failure is a show-stopper. Failure = useful error message.

Implement termination in try/finallytry/finally to guarantee its execution.

It is sometimes convenient to wrap the call to a large function in a single trytry statement rather than putting many trytry statements inside of the function.

Page 19: Chapter 24 Exception CSC1310 Fall 2009. Exceptions Exceptions Exceptions are events that can modify the flow or control through a program. They are automatically

Do not Catch Too MuchDo not Catch Too Much Do not catch too much (system exits, memory errors,

programming mistakes, iteration stops.)import sysdef bye(): sys.exit(40)try: bye()except: print “got it”print “continue”

Mydictionary={…}try: x=Myditctionary[‘ok’]except: x=None #KeyError #continue Be specific in your handlers: empty except are handy,

but potentially error-prone.

Page 20: Chapter 24 Exception CSC1310 Fall 2009. Exceptions Exceptions Exceptions are events that can modify the flow or control through a program. They are automatically

Do not Catch Too LittleDo not Catch Too Little Do not use too specific handlers: you will

need to add new exceptions to exception list in future.

Instead, careful use of class-based exception can help here.

>>>try: … except(myer1,myer2): … else …>>>try:… except SuccessCategoryName: … else: …