exception handling - hacettepe Üniversitesikeywords of exception handling • thereare fivekeywords...

30
Exception Handling BBM 101 - Introduction to Programming I Hacettepe University Fall 2016 Fuat Akal, Aykut Erdem, Erkut Erdem 1

Upload: others

Post on 10-Aug-2020

6 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Exception Handling - Hacettepe ÜniversitesiKeywords of Exception Handling • Thereare fivekeywords in Python to dealwith exceptions: try, except, else, raiseand finally. • try:

ExceptionHandling

BBM101- Introduction toProgramming I

Hacettepe UniversityFall2016

FuatAkal,Aykut Erdem,ErkutErdem

1

Page 2: Exception Handling - Hacettepe ÜniversitesiKeywords of Exception Handling • Thereare fivekeywords in Python to dealwith exceptions: try, except, else, raiseand finally. • try:

WhatisanException?• Anexceptionisanabnormalcondition(andthusrare)that

arisesinacodesequenceatruntime.Forinstance:– Dividinganumberbyzero– Accessinganelementthatisoutofboundsofanarray– Attemptingtoopenafilewhichdoesnotexist

• Whenanexceptionalconditionarises,anobjectrepresentingthatexceptioniscreatedandthrowninthecodethatcausedtheerror

• Anexceptioncanbecaughttohandleitorpassiton

• Exceptionscanbegeneratedbytherun-timesystem,ortheycanbemanuallygeneratedbyyourcode

2

Page 3: Exception Handling - Hacettepe ÜniversitesiKeywords of Exception Handling • Thereare fivekeywords in Python to dealwith exceptions: try, except, else, raiseand finally. • try:

WhatisanException?

test = [1,2,3]test[3]

3

IndexError: list index out of range

Page 4: Exception Handling - Hacettepe ÜniversitesiKeywords of Exception Handling • Thereare fivekeywords in Python to dealwith exceptions: try, except, else, raiseand finally. • try:

WhatisanException?successFailureRatio = numSuccesses/numFailures

print('The success/failure ratio is', successFailureRatio)

print('Now here')

4

ZeroDivisionError: integer division or modulo by zero

Page 5: Exception Handling - Hacettepe ÜniversitesiKeywords of Exception Handling • Thereare fivekeywords in Python to dealwith exceptions: try, except, else, raiseand finally. • try:

WhatisanException?val = int(input('Enter an integer: '))

print('The square of the number you entered is', val**2)

> Enter an integer: asd

5

ValueError: invalid literal for int() with base 10: 'asd'

Page 6: Exception Handling - Hacettepe ÜniversitesiKeywords of Exception Handling • Thereare fivekeywords in Python to dealwith exceptions: try, except, else, raiseand finally. • try:

HandlingExceptions• Exceptionmechanism gives the programmer achance to do

something against anabnormal condition.

• Exception handling isperforming anaction inresponse to anexception.

• This actionmay be:– Exiting the program– Retrying the actionwith or without alternative data– Displayinganerrormessage andwarninguser to dosomething– ....

6

Page 7: Exception Handling - Hacettepe ÜniversitesiKeywords of Exception Handling • Thereare fivekeywords in Python to dealwith exceptions: try, except, else, raiseand finally. • try:

HandlingExceptionstry:

successFailureRatio = numSuccesses/numFailures

print('The success/failure ratio is', successFailureRatio)

Except ZeroDivisionError:

print('No failures, so the success/failure is undefined.')

print('Now here')

7

• Uponenteringthetry block,theinterpreterattemptstoevaluatetheexpressionnumSuccesses/numFailures.

• Ifexpressionevaluationissuccessful,theassignmentisdoneandtheresultisprinted.

• If,however,aZeroDivisionError exceptionisraised,theprintstatementintheexcept blockisexecuted.

Page 8: Exception Handling - Hacettepe ÜniversitesiKeywords of Exception Handling • Thereare fivekeywords in Python to dealwith exceptions: try, except, else, raiseand finally. • try:

while True: val = input('Enter an integer: ') try:

val = int(val) print('The square of the number you entered is', val**2) break #to exit the while loop

except ValueError: print(val, 'is not an integer')

8

HandlingExceptions

ChecksforwhetherValueError exceptionisraisedornot

Page 9: Exception Handling - Hacettepe ÜniversitesiKeywords of Exception Handling • Thereare fivekeywords in Python to dealwith exceptions: try, except, else, raiseand finally. • try:

KeywordsofExceptionHandling

• There are five keywords inPython to deal withexceptions:try,except,else,raise and finally.

• try:Creates ablock to monitor if any exceptionoccurs.

• except:Follows the try block and catches anyexception which isthrownwithin it.

9

Page 10: Exception Handling - Hacettepe ÜniversitesiKeywords of Exception Handling • Thereare fivekeywords in Python to dealwith exceptions: try, except, else, raiseand finally. • try:

AreThereManyExceptionsinPython?

• Yes,someofthemare…– Exception– ArithmeticError– OverflowError– ZeroDivisonError– EOFError– NameError– IOError– SyntaxError

10

Listofallexceptions(errors):http://docs.python.org/3/library/exceptions.html#bltin-exceptions

Page 11: Exception Handling - Hacettepe ÜniversitesiKeywords of Exception Handling • Thereare fivekeywords in Python to dealwith exceptions: try, except, else, raiseand finally. • try:

MultipleexceptStatements

11

• It ispossible that more than one exception canbethrown inacode block.– Wecanusemultipleexcept clauses

• Whenanexceptionisthrown,eachexcept statementisinspectedinorder,andthefirstonewhosetypematches thatoftheexceptionisexecuted.– Type matchingmeans that the exception thrownmust beanobject of

the same class or asub-class ofthe declared class inthe exceptstatement

• Afteroneexcept statementexecutes,theothersarebypassed.

Page 12: Exception Handling - Hacettepe ÜniversitesiKeywords of Exception Handling • Thereare fivekeywords in Python to dealwith exceptions: try, except, else, raiseand finally. • try:

MultipleexceptStatements

12

try:

Youdoyouroperationshere;except Exception-1:

Executethisblock.except Exception-2:

Executethisblock.except (Exception-3[, Exception-4[,...ExceptionN]]]):

Ifthereisanyexceptionfromthegivenexceptionlist,thenexecutethisblock.

except (ValueError, TypeError):…

Theexceptblockwillbeenteredifanyofthelistedexceptions israisedwithinthetryblock

Page 13: Exception Handling - Hacettepe ÜniversitesiKeywords of Exception Handling • Thereare fivekeywords in Python to dealwith exceptions: try, except, else, raiseand finally. • try:

MultipleexceptStatementstry:

f = open('outfile.dat', 'w')dividend = 5divisor = 0division = dividend / divisorf.write(str(division))

except IOError:print("I can't open the file!")

except ZeroDivisionError:print("You can't divide by zero!")

13

Youcan'tdividebyzero!

Page 14: Exception Handling - Hacettepe ÜniversitesiKeywords of Exception Handling • Thereare fivekeywords in Python to dealwith exceptions: try, except, else, raiseand finally. • try:

MultipleexceptStatementstry:

f = open('outfile.dat', 'w')dividend = 5divisor = 0division = dividend / divisorf.write(str(division))

except Exception:print("Exception occured and handled!")

except IOError:print("I can't open the file!")

except ZeroDivisionError:print("You can't divide by zero!")

14

Exceptionoccured andhandled!

Page 15: Exception Handling - Hacettepe ÜniversitesiKeywords of Exception Handling • Thereare fivekeywords in Python to dealwith exceptions: try, except, else, raiseand finally. • try:

MultipleexceptStatementstry:

f = open('outfile.dat', 'w')dividend = 5divisor = 0division = dividend / divisorf.write(str(division))

except:print("Exception occured and handled!")

except IOError:print("I can't open the file!")

except ZeroDivisionError:print("You can't divide by zero!")

15

SyntaxError: default 'except:' must be last

Page 16: Exception Handling - Hacettepe ÜniversitesiKeywords of Exception Handling • Thereare fivekeywords in Python to dealwith exceptions: try, except, else, raiseand finally. • try:

except-elseStatements

16

try:You do your operations here

except: Execute this block.

else: If there is no exception then execute this block.

try:f = open(arg, 'r')

except IOError:print('cannot open', arg)

else:print(arg, 'has', len(f.readlines()), 'lines')

Page 17: Exception Handling - Hacettepe ÜniversitesiKeywords of Exception Handling • Thereare fivekeywords in Python to dealwith exceptions: try, except, else, raiseand finally. • try:

finallyStatement

17

• finally creates ablock ofcode that will beexecuted afteratry/except block hascompletedand before the codefollowingthe try/except block

• finally block isexecuted whether or notexception isthrown

• finally block isexecuted whether or notexception iscaught

• It isused to gurantee that acode blockwill beexecuted inanycondition.

Page 18: Exception Handling - Hacettepe ÜniversitesiKeywords of Exception Handling • Thereare fivekeywords in Python to dealwith exceptions: try, except, else, raiseand finally. • try:

finallyStatement

18

Youcanuseittocleanupfiles,databaseconnections,etc.

try:You do your operations here

except: Execute this block.

finally: This block will definitely be executed.

try: file = open('out.txt', 'w') do something…

finally: file.close()os.path.remove('out.txt')

Page 19: Exception Handling - Hacettepe ÜniversitesiKeywords of Exception Handling • Thereare fivekeywords in Python to dealwith exceptions: try, except, else, raiseand finally. • try:

NestedtryBlocks• When anexception occurs insideatry block;

– If thetry block does nothave amatchingexcept,then the outertrystatement’s except clauses are inspected for amatch

– If amatchingexcept isfound,that except block isexecuted– If nomatchingexcept exists,execution flowcontinues to find a

matchingexcept by inspecting the outer try statements– If amatchingexcept cannot befound atall,the exceptionwill be

caught by Python’s exception handler.

• Execution flow never returns to the line that exception wasthrown.This means,anexception iscaught and except blockisexecuted,the flow will continuewith the lines followingthisexcept block

19

Page 20: Exception Handling - Hacettepe ÜniversitesiKeywords of Exception Handling • Thereare fivekeywords in Python to dealwith exceptions: try, except, else, raiseand finally. • try:

Let’s clarify itonvarious scenarios

20

try:statement1try:

statement2except Exception1:

statement3except Exception2:

statement4;try:

statement5except Exception3:

statement6statement7;

except Exception3:statement8

statement9;

Information: Exception1andException2aresubclassesofException3

Question:Whichstatementsareexecutedif1- statement1throwsException12- statement2throwsException13- statement2throwsException34- statement2throwsException1andstatement3throws Exception2

Page 21: Exception Handling - Hacettepe ÜniversitesiKeywords of Exception Handling • Thereare fivekeywords in Python to dealwith exceptions: try, except, else, raiseand finally. • try:

Scenario:statement1throws Exception1

21

try:statement1try:

statement2except Exception1:

statement3except Exception2:

statement4;try:

statement5except Exception3:

statement6statement7;

except Exception3:statement8

statement9;

Exception1Step1:Exceptionisthrown

Step2:except clauses ofthetryblockareinspectedforamatching except statement.Exception3issuperclassofException1,soitmatches.

Step3:statement8isexecuted,exceptionishandledandexecutionflowwillcontinuebypassing thefollowing except clauses

Step4:statement9isexecuted

Page 22: Exception Handling - Hacettepe ÜniversitesiKeywords of Exception Handling • Thereare fivekeywords in Python to dealwith exceptions: try, except, else, raiseand finally. • try:

Scenario:statement2throws Exception1

22

try:statement1try:

statement2except Exception1:

statement3except Exception2:

statement4;try:

statement5except Exception3:

statement6statement7;

except Exception3:statement8

statement9;

Exception1Step1:Exceptionisthrown

Step2:except clauses ofthetryblockareinspectedforamatching except statement.Firstclausecatchestheexception

Step3:statement3isexecuted,exceptionishandled

Step4:executionflowwillcontinuebypassing thefollowing except clauses.statement5isexecuted.

Step5:Assumingnoexceptionisthrownbystatement5,programcontinueswithstatement7andstatement9.

Page 23: Exception Handling - Hacettepe ÜniversitesiKeywords of Exception Handling • Thereare fivekeywords in Python to dealwith exceptions: try, except, else, raiseand finally. • try:

Scenario:statement2throws Exception3

23

try:statement1try:

statement2except Exception1:

statement3except Exception2:

statement4;try:

statement5except Exception3:

statement6statement7;

except Exception3:statement8

statement9;

Exception3Step1:Exceptionisthrown

Step2:except clauses ofthetryblockareinspectedforamatching except statement.Noneofthese except clauses matchException3

Step3:except clauses oftheoutertrystatementareinspectedforamatching except .Exception3iscatchedandstatement8isexecuted

Step4:statement9isexecuted

Page 24: Exception Handling - Hacettepe ÜniversitesiKeywords of Exception Handling • Thereare fivekeywords in Python to dealwith exceptions: try, except, else, raiseand finally. • try:

Scenario:statement2throws Exception1and statement3throws Exception2

24

try:statement1try:

statement2except Exception1:

statement3except Exception2:

statement4;try:

statement5except Exception3:

statement6statement7;

except Exception3:statement8

statement9;

Exception1Step1:Exceptionisthrown

Step2:Exceptioniscatchedandstatement3isexecuted.

Step3:statement3throwsanewexception

Step5:statement9isexecuted

Exception2

Step4:Except clauses oftheoutertrystatementareinspectedforamatching except.Exception2iscatchedandstatement8isexecuted

Page 25: Exception Handling - Hacettepe ÜniversitesiKeywords of Exception Handling • Thereare fivekeywords in Python to dealwith exceptions: try, except, else, raiseand finally. • try:

raise Statement

• Youcanraiseexceptionsbyusingtheraisestatement.

• Thesyntaxisasfollows:raise exceptionName(arguments)

25

Page 26: Exception Handling - Hacettepe ÜniversitesiKeywords of Exception Handling • Thereare fivekeywords in Python to dealwith exceptions: try, except, else, raiseand finally. • try:

raise Statementdef getRatios(vect1, vect2):

""" Assumes: vect1 and vect2 are equal length lists of numbersReturns: a list containing the meaningful values of vect1[i]/vect2[i]

"""ratios = []for index in range(len(vect1)):

try:ratios.append(vect1[index]/vect2[index])

except ZeroDivisionError:ratios.append(float('nan')) #nan = Not a Number

except:raise ValueError(’getRatios called with bad arguments’)

return ratios

try:print(getRatios([1.0, 2.0, 7.0, 6.0], [1.0,2.0,0.0,3.0]))print(getRatios([], []))print(getRatios([1.0, 2.0], [3.0]))

except ValueError as msg:print(msg) 26

[1.0, 1.0, nan, 2.0][]getRatios called with bad arguments

Page 27: Exception Handling - Hacettepe ÜniversitesiKeywords of Exception Handling • Thereare fivekeywords in Python to dealwith exceptions: try, except, else, raiseand finally. • try:

raise Statement

• AvoidraisingagenericException! Tocatchit,you'llhavetocatchallothermorespecificexceptionsthatsubclassit..

27

def demo_bad_catch(): try:

raise ValueError('a hidden bug, do not catch this')raise Exception('This is the exception you expect to handle')

except Exception as error:print('caught this error: ' + repr(error))

>>> demo_bad_catch()caught this error: ValueError('a hidden bug, do not catch this',)

Page 28: Exception Handling - Hacettepe ÜniversitesiKeywords of Exception Handling • Thereare fivekeywords in Python to dealwith exceptions: try, except, else, raiseand finally. • try:

raise Statement

• andmorespecificcatcheswon'tcatchthegeneralexception:..

28

def demo_no_catch(): try:

raise Exception('general exceptions not caught by specific handling')except ValueError as e:

print('we will not catch e')

>>> demo_no_catch()Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in demo_no_catch

Exception: general exceptions not caught by specific handling

Page 29: Exception Handling - Hacettepe ÜniversitesiKeywords of Exception Handling • Thereare fivekeywords in Python to dealwith exceptions: try, except, else, raiseand finally. • try:

CustomExceptions

29

• UserscandefinetheirownexceptionbycreatinganewclassinPython.

• Thisexceptionclasshastobederived,eitherdirectlyorindirectly,fromExceptionclass.

• Mostofthebuilt-inexceptionsarealsoderivedformthisclass.

Page 30: Exception Handling - Hacettepe ÜniversitesiKeywords of Exception Handling • Thereare fivekeywords in Python to dealwith exceptions: try, except, else, raiseand finally. • try:

CustomExceptionsclass ValueTooSmallError(Exception):

"""Raised when the input value is too small"""pass

class ValueTooLargeError(Exception):"""Raised when the input value is too large"""pass

number = 10 # you need to guess this number

while True:try:

i_num = int(input("Enter a number: "))if i_num < number:

raise ValueTooSmallErrorelif i_num > number:

raise ValueTooLargeErrorbreak

except ValueTooSmallError:print("This value is too small, try again!")

except ValueTooLargeError:print("This value is too large, try again!")

print("Congratulations! You guessed it correctly.") 30