Title | Discussion Forum Unit 8 |
---|---|
Course | Programming Fundamentals |
Institution | University of the People |
Pages | 2 |
File Size | 84.2 KB |
File Type | |
Total Downloads | 81 |
Total Views | 152 |
Discussion Forum Unit 8...
In Python, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause. We can thus choose what operations to perform once we have caught the exception. Here is a simple example.
import sys List = ['Hello', 0, '' , 10] for entry in List: try: print("The entry is", entry) r = 1/int(entry) break except: print("Oh!", sys.exc_info()[0], "occurred.") print("Next entry.") print() print("The reciprocal of", entry, "is", r)
The output: The entry is Hello Oh! occurred. Next entry.
The entry is 0 Oh! occurred. Next entry.
The entry is Oh! occurred. Next entry.
The entry is 10 The reciprocal of 10 is 0.1
I think if I had to deal with a large production program I would first, try to put a big section of the code in a try statement and if an error is caught there, I will try to look deeper in that section by reducing the amount of code inside the try statement until eventually, I would find the exact part of the code that is not working. Also is better to incorporate specific exception that will recover and handle such error that could happen during the use of the program, such like except TypeError – ValueError.
References:
Python Exception Handling Using try, except and finally statement. (n.d.). Programiz. https://www.programiz.com/python-programming/exception-handling...