
Understanding Python Error Handling
Learn about Python exceptions and how to handle errors like accessing variables that don't exist or dividing by zero. Discover how to use try-except blocks to catch exceptions and how to raise custom exceptions when needed.
Download Presentation

Please find below an Image/Link to download the presentation.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.
You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.
E N D
Presentation Transcript
Error Handling CSEG Python Training, Week 9
Exceptions What happens when something goes wrong like using an index beyond the length of a list, accessing a variable that doesn t exist, or dividing by zero? Python will raise an Exception on the line that failed. Exceptions are special Python objects that contain error information: What type of error was encountered. A message describing what went wrong. What line failed, and in which file/module/function. How that line was reached. Exceptions can potentially be intercepted( caught ) and responded to. If an exception isn t caught, then the program will terminate and error information will be printed to standard error.
stack_trace.py Call Stack Error Type Message
stack_trace.py Read From Bottom To Top File Scope Line Line Number
Catching Exceptions Sometimes you can anticipate that something may go wrong and you would like to respond to it rather than having the program crash. EX: A few fields in an otherwise usable file contain bad values. When an exception is raised, processing terminates on that line and the exception propagates up the call stack until it is either caught, or the call stack ends. You catch an exception using a try, except block.
Raising Exceptions Let s say that you have a function that takes an input variable foo. foo shouldn t be negative, otherwise the function will return an incorrect result. You can detect if foo is negative and use the raise keyword to notify the calling code that the function received a bad foo value. Takes the form: raise TheExceptionClass( Your error message ) You can find Python s built-in Exceptions here. In this case, we would use a ValueError since the value of the foo variable is incorrect. You can also create your own type of error by inheriting from Exception In general, you should try to use one of the built-in Exceptions whenever possible. We ll revisit inheritance in the future. EX: class MyCustomException(Exception): pass
Side Note About Raising Exceptions When writing a function, it s a good idea to check your input for validity and raise an exception if your conditions for validity are not met. It s also a good idea to do this for your output/side-effects as well. This helps your code to fail-fast .
Can You Catch Every Exception? Yes, but you probably shouldn t. Crashes are good actually. Your code terminates as soon as it detects an error and loudly announces what happened and how it got there. Again, we want our code to fail-fast. Catching everything will silently let your code cause additional problems whose root cause is unclear. When writing try/except clauses, it s best to select the specific exceptions you can recover from rather than trying to intercept anything that might go wrong. However...
Catching Everything If you re processing a million files in a batch, you may want to catch any type of error that occurs in your processing loop, log the error, and then continue processing. This is done by using except without specifying an Exception class to catch. Alternatively, you can use except Exception: You actually want to catch everything except the KeyboardInteruptError so you can terminate your processing with ctrl+c. This is done by using multiple except blocks, one that catches just the KeyboardInteruptError and then re-raises it, and another that catches everything else. Python s logging and traceback modules allow you to easily log/print a caught exception. We ll get back to these later. Use this technique very carefully. Notice that under the right circumstances, you could do some operation incorrectly a million times and not know until you examined the logs.
else & finally Writing an exception block but using else instead of except will execute code in the block if no error is encountered. Writing an exception block using finally instead of except will cause the code in the block to always be executed. Rarely used, but you may encounter them.
Homework 1. Attempt to open a file that does not exist. 2. Attempt to open a file that does not exist, but prevent the code from crashing. a. Use a try/except clause to print No file! when the open fails. b. Print Reached end of program. at the end of the program and outside of the try/except clause to verify the program ended normally. 3. Re-raise the exception. a. Do the same as 2, but re-raise the exception after you print No file! . b. This should crash the program.
Homework Cont. 4. Convert a string to a list of integers while ignoring bad values: a. Create a variable containing this string: 1, 2, 3, oops, 5 b. Split the string using , as the delimiter. c. Create an empty list to store your integers. d. Iterate over the elements of the split string: i. for token in split_string: e. Convert each element of the split string into an integer. i. (Remember int(your_string) will do the conversion.) f. Use a try/except clause to ignore the bad value. i. Print the bad value if the conversion fails. g. Append the integer to the list you created. h. After storing all the integers in your list, print the list.
Example Files You can get copies of the example files with the following command: git clone https://gitlab.com/CSU-CIRA/python_training_resources/exceptions.git You can also download them from here: https://drive.google.com/drive/folders/1duVsM531VnWgRVJYpGZnTUWC9gYxbr_b?usp=shar ing