1. Exception Statement
1.1 try - except statement
If there is any error while executing codes under try statement, then code under except statement will execute. There are three types of try - except statement.
- try - except : Codes under except statement will execute whatever error it is.
- try - except [Raised Error] : Codes under statement except will execute when error is in written case.
- try - except [Raised Error] as [Alias] : Codes under except statement will execute when error is in wrriten case and store contents in aliased variable.
try:
self.ser = serial.Serial(self.port, 9600, timeout=self.timeout)
except serial.SerialException as e:
self.ser = None
logger.exception('Error opening serial: %s', e)
1.2 try - finally statement
Codes under finally block always executes whatever error it is. Usually finally statement is used when we close using resource.
def send_db(file):
reader = csv.reader(file)
header = next(reader)
try:
conn = sqlite3.connect('arduino.db')
cursor = conn.cursor()
# Error if there is previous User_name and Date
for row in reader:
query = f"INSERT INTO arduino VALUES (?, ?, ?, ?, ?);"
cursor.execute(query, (row[0], row[1], row[2], row[3], row[4]))
conn.commit()
finally:
conn.close()
print("Uploading work has been done!")
1.3 Dealing multiple errors
If we want to process multiple errors, we can use multiple except statement like using if - elif statement.
try:
print("Let's start the codes")
except [RaisedError1]:
print("Error1 is raised!")
except [RaisedError2]:
print("Error2 is raised!")
If we want to execute codes when there is no errors after try statement, else statement can help works.
try:
print("Let's start the program!")
except [RaisedError1] as [Error1]:
print("{Error1} is raised!")
else:
# This statement will execute only there is no error in try statement.
# finally statement alwalys execute whatever error it is.
print("There is no error!")
1.4 Raising error on purpose
When we make program, we need to raise error on purpose. raise command can raise error. For example, when we make class which its heritated class must define fly again, then we can make class Bird below :
class Bird:
def fly(self):
raise NotImplementedError
So when we define new class heritating class Bird and if new class didn't define fly method, then fly method of Bird class will return NotImplementedError.
Source from : https://wikidocs.net/30
'Language > Python' 카테고리의 다른 글
[folium] Visualization Map on Python (0) | 2022.09.18 |
---|---|
[heapq] Implementing Binary Heap in Python (0) | 2022.09.14 |
[queue] Implementing Priority Queue in Python (0) | 2022.09.14 |
[beautifultable] Print List in Table Format (0) | 2022.09.14 |
[beautifulsoup] Web Scraping (0) | 2022.09.13 |