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”

Slides:



Advertisements
Similar presentations
Exception Handling Genome 559. Review - classes 1) Class constructors - class myClass: def __init__(self, arg1, arg2): self.var1 = arg1 self.var2 = arg2.
Advertisements

A Crash Course Python. Python? Isn’t that a snake? Yes, but it is also a...
1 Exception-Handling Overview Exception: when something unforeseen happens and causes an error Exception handling – improves program clarity by removing.
Introduction to Computing Using Python Exceptions (Oops! When things go wrong)  Errors and Exceptions  Syntax errors  State (execution) errors.
Lecture 07 – Exceptions.  Understand the flow of control that occurs with exceptions  try, except, finally  Use exceptions to handle unexpected runtime.
 2002 Prentice Hall. All rights reserved Exception-Handling Overview Exception handling –improves program clarity and modifiability by removing.
Exceptions COMPSCI 105 S Principles of Computer Science.
Python Mini-Course University of Oklahoma Department of Psychology Lesson 19 Handling Exceptions 6/09/09 Python Mini-Course: Lesson 19 1.
WEEK EXCEPTION HANDLING. Syntax Errors Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while.
November 15, 2005ICP: Chapter 7: Files and Exceptions 1 Introduction to Computer Programming Chapter 7: Files and Exceptions Michael Scherger Department.
17. Python Exceptions Handling Python provides two very important features to handle any unexpected error in your Python programs and to add debugging.
General Programming Introduction to Computing Science and Programming I.
Exceptions 2 COMPSCI 105 S Principles of Computer Science.
Python – May 17 Recap lab Multidimensional list Exceptions Commitment: quiz tomorrow.
Functions Reading/writing files Catching exceptions
Guide to Programming with Python Chapter Seven (Part 1) Files and Exceptions: The Trivia Challenge Game.
Dealing with Errors. Error Types Syntax Errors Runtime Errors Logical Errors.
Exceptions COMPSCI 105 SS 2015 Principles of Computer Science.
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Cem Sahin CS  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions.
1. Understand how to catch errors in a program 2. Know how to filter user input to stop incorrect data.
Guide to Programming with Python Chapter Seven Files and Exceptions: The Trivia Challenge Game.
CS 127 Exceptions and Decision Structures. Exception Handling This concept was created to allow a programmer to write code that catches and deals with.
Introduction to Computing Using Python Exceptions (Oops! When things go wrong)  Errors and Exceptions  Syntax errors  State (execution) errors.
Lecture 4 Python Basics Part 3.
Python Built-in Exceptions Data Fusion Albert Esterline Source:
Lecture 07 – Exceptions.  Understand the flow of control that occurs with exceptions  try, except, finally  Use exceptions to handle unexpected runtime.
Exception Handling and String Manipulation. Exceptions An exception is an error that causes a program to halt while it’s running In other words, it something.
Python Exceptions and bug handling Peter Wad Sackett.
Head First Python: Ch 3. Files and Exceptions: Dealing with Errors Aug 26, 2013 Kyung-Bin Lim.
EXCEPTIONS. Catching exceptions Whenever a runtime error occurs, it create an exception object. The program stops running at this point and Python prints.
Python: Revision Damian Gordon. Python: Structured Programming Damian Gordon.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Python: File Management Damian Gordon. File Management We’ve seen a range of variable types: – Integer Variables – Real Variables – Character Variables.
Exceptions in Python Error Handling.
Introduction to Computing Science and Programming I
George Mason University
CS170 – Week 1 Lecture 3: Foundation Ismail abumuhfouz.
Example: Vehicles What attributes do objects of Sedan have?
Files and Exceptions: The Trivia Challenge Game
Lecture 4 Python Basics Part 3.
Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Exceptions and File Input
Handling errors try except
Exceptions and files Taken from notes by Dr. Neil Moore
Exceptions 10-Nov-18.
Exception Handling Chapter 9.
Advanced Java Programming
Topics Introduction to File Input and Output
Chapter 7 Files and Exceptions
Exception Handling.
Python’s Errors and Exceptions
Chapter 12 Exception Handling
Exceptions and files Taken from notes by Dr. Neil Moore
Lecture 4 Python Basics Part 3.
ERRORS AND EXCEPTIONS Errors:
(Oops! When things go wrong)
Exceptions.
Problems Debugging is fine and dandy, but remember we divided problems into compile-time problems and runtime problems? Debugging only copes with the former.
Advanced Python Concepts: Exceptions
Python Syntax Errors and Exceptions
Advanced Python Concepts: Exceptions
By Ryan Christen Errors and Exceptions.
Exceptions 10-May-19.
Exception Handling COSC 1323.
CSE 231 Lab 5.
Topics Introduction to File Input and Output
Python Exceptions and bug handling
UW CSE 190p Section 7/19, Summer 2012 Dun-Yu Hsiao.
Dealing with Runtime Errors
Presentation transcript:

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” (since something exceptional has occurred). We say that “Python raises an exception” when an error occurs.

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

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'

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.

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.

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.

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.

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

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

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

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

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.

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.

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

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

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!”)

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

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.

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!”)

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)

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.

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!'

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.

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.

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.

etc.