Presentation is loading. Please wait.

Presentation is loading. Please wait.

Python: Exception Handling Damian Gordon. Exception Handling When an error occurs in a program that causes the program to crash, we call that an “exception”

Similar presentations


Presentation on theme: "Python: Exception Handling Damian Gordon. Exception Handling When an error occurs in a program that causes the program to crash, we call that an “exception”"— Presentation transcript:

1 Python: Exception Handling Damian Gordon

2 Exception Handling When an error occurs in a program that causes the program to crash, we call that an “exception” (since something exceptional has occurred). We say that “Python raises an exception” when an error occurs.

3 Exception Handling What happens if we try to open a file that doesn’t exist?

4 Exception Handling What happens if we try to open a file that doesn’t exist? >>> Traceback (most recent call last): File "C:\Python34\FileRead.py", line 3, in file_pointer = open("C:\Python34\MyDtaa.txt", "r") FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Python34\\MyDtaa.txt'

5 Exception Handling Python has a way of intercepting the exceptions (and handling it) before the program crashes, and exiting gracefully. Using the try and except commands.

6 Exception Handling # PROGRAM ExceptionHanding1 try: file_pointer = open("C:\Python34\FakeFile.txt", "r") print(file_pointer.read()) file_pointer.close() except: print("Something went wrong") # END.

7 Exception Handling # PROGRAM ExceptionHanding1 try: file_pointer = open("C:\Python34\FakeFile.txt", "r") print(file_pointer.read()) file_pointer.close() except: print("Something went wrong") # END. IF (There is no problem opening the file) THEN ELSE ENDIF; END.

8 Exception Handling If we are asking for the user to input the filename we want to open, it is very important that we include an exception handling block to make sure we deal with the case of the user typing in the wrong filename.

9 Exception Handling # PROGRAM ExceptionHandling2 NameOfFile = str(input("What File would you like to read: ")) PathName = "C:\\Python34\\" Extension = ".txt" FullFileName = PathName + NameOfFile + Extension file_pointer = open(FullFileName, "r") print(file_pointer.read()) file_pointer.close() # END. Without the exception block

10 Exception Handling # PROGRAM ExceptionHandling2 NameOfFile = str(input("What File would you like to read: ")) PathName = "C:\\Python34\\" Extension = ".txt" FullFileName = PathName + NameOfFile + Extension try: file_pointer = open(FullFileName, "r") print(file_pointer.read()) file_pointer.close() except: print("No file of that name found") # END. With the exception block

11 Exception Handling Python can detect different types of exceptions, including: – Input/Output exceptions – File indexing exceptions – Directory key exceptions – Variable naming exceptions – Syntax exceptions – Type exceptions – Argument exceptions – Divide-by-zero exceptions

12 Exception Handling Exception TypeDescription IOError Raised when trying to read or write a non-existent file IndexError Raised when an array element that doesn’t exist is named KeyError Raised when a dictionary key is not found NameError Raised when the name of variable or function is not found SyntaxError Raised when a syntax error in the code is detected TypeError Raised when an inappropriate type is detected ValueError Raised when a problem with the value passed in is detected ZeroDivisionError Raised when denominator of a division is zero

13 Exception Handling # PROGRAM ExceptionHandling3 try: InputValue = int(input("Please Input a Value: ")) print("The value input was", InputValue) except ValueError: print("Dude, you didn't type in a number!") # END.

14 Exception Handling # PROGRAM ExceptionHandling3 try: InputValue = int(input("Please Input a Value: ")) print("The value input was", InputValue) except ValueError: print("Dude, you didn't type in a number!") # END. Checking for a ValueError.

15 Exception Handling We can handle multiple exceptions together by listing them in a single except clause. For example: except(TypeError, ValueError):

16 Exception Handling # PROGRAM ExceptionHandling4 for InputValue in (None, "Hi!"): # DO try: print(float(InputValue)) except(TypeError, ValueError): print("Something went wrong!") # ENDFOR; # END.

17 Exception Handling # PROGRAM ExceptionHandling4 for InputValue in (None, "Hi!"): # DO try: print(float(InputValue)) except(TypeError, ValueError): print("Something went wrong!") # ENDFOR; # END. Checking for a TypeError and ValueError. TypeError: float(None) ValueError: float(“Hi!”)

18 Exception Handling We can also handle multiple exceptions individually by listing them in a seperate except clauses. For example: except TypeError: except ValueError:

19 Exception Handling # PROGRAM ExceptionHandling5 for InputValue in (None, "Hi!"): # DO try: print(float(InputValue)) except TypeError: print("Type Error: Dude, you typed in a NULL value”) except ValueError: print("Value Error: Dude, you typed in characters") # ENDFOR; # END.

20 Exception Handling # PROGRAM ExceptionHandling5 for InputValue in (None, "Hi!"): # DO try: print(float(InputValue)) except TypeError: print("Type Error: Dude, you typed in a NULL value”) except ValueError: print("Value Error: Dude, you typed in characters") # ENDFOR; # END. Checking for a TypeError and ValueError. TypeError: float(None) ValueError: float(“Hi!”)

21 Exception Handling When an exception occurs, that exception passes a system message back to the program as well that can be printed out. For example: except TypeError as SysMessage: print("System Message:", SysMessage)

22 Exception Handling # PROGRAM ExceptionHandling6 for InputValue in (None, "Hi!"): # DO try: print(float(InputValue)) except(TypeError, ValueError) as SysMessage: print("Something went wrong!") print("System Message:", SysMessage) # ENDFOR; # END.

23 Exception Handling # PROGRAM ExceptionHandling6 for InputValue in (None, "Hi!"): # DO try: print(float(InputValue)) except(TypeError, ValueError) as SysMessage: print("Something went wrong!") print("System Message:", SysMessage) # ENDFOR; # END. System Message: float() argument must be a string or a number, not 'NoneType' System Message: could not convert string to float: 'Hi!'

24 Exception Handling For can also add a single else statement to the except block. This else statement is executed if no exceptions are raised in the try block.

25 Exception Handling # PROGRAM ExceptionHandling7 try: InputValue = int(input("Please Input a Value: ")) except ValueError: print("Dude, you didn't type in a number!") else: print("The value input was", InputValue) # END.

26 Exception Handling # PROGRAM ExceptionHandling7 try: InputValue = int(input("Please Input a Value: ")) except ValueError: print("Dude, you didn't type in a number!") else: print("The value input was", InputValue) # END. An ELSE statement after the EXCEPT block allows the program to let the user know that the TRY statement suceeded.

27 etc.


Download ppt "Python: Exception Handling Damian Gordon. Exception Handling When an error occurs in a program that causes the program to crash, we call that an “exception”"

Similar presentations


Ads by Google