Exception Handling¶
Exceptions are mechanism for handling runtime errors. A simple example:
dict = {"a":1, "b":2, "c":3}
print(dict["d"])
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-2-0175b692bf59> in <module> 1 dict = {"a":1, "b":2, "c":3} ----> 2 print(dict["d"]) KeyError: 'd'
KeyError is the exception that was raised. We can check for this and take the appropriate action instead
try:
val = dict["d"]
except KeyError:
val = "error that key is not found"
print(val)
error that key is not found
We have yet to talk about I/O, but when you open a file, you would get an error if the file does not exist.
try:
f = open("file.txt", "r")
except IOError:
print("error: that file does not exist")
error: that file does not exist
We can also get the detail of the exception, and re-raise the exception.
try:
1/0
except ZeroDivisionError as detail:
print("Handling run-time error: ", detail)
raise
Handling run-time error: division by zero
--------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) <ipython-input-5-6628859c5c39> in <module> 1 try: ----> 2 1/0 3 except ZeroDivisionError as detail: 4 print("Handling run-time error: ", detail) 5 raise ZeroDivisionError: division by zero
There are many different types of exceptions. You probably won't be able to anticipate every failure mode in advance. In that case, when you run and your code crashes because of an exception, the python interpreter will print out the name of the exception and you can then modify your code to take the appropriate action.
You can catch multiple ones per except clause or have multiple except clauses. You can also use an else clause after successful execution, and a finally clause, which is always executed before exiting the try block.
import sys
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except OSError as err:
print("OS error: {0}".format(err))
except ValueError:
print("Could not convert data to an integer.")
raise
except:
print("Unexpected error:", sys.exc_info()[0])
raise
else:
print('Success')
finally:
print('Goodbye!')
Could not convert data to an integer. Goodbye!
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-4-ac2a77cf844b> in <module> 4 f = open('myfile.txt') 5 s = f.readline() ----> 6 i = int(s.strip()) 7 except OSError as err: 8 print("OS error: {0}".format(err)) ValueError: invalid literal for int() with base 10: '100ee'
You can have your own functions raise exceptions when things go wrong and you can build your own exception classes (more later).
'Python' 카테고리의 다른 글
| 6. Recursion vs. Iteration (1) | 2024.03.14 |
|---|---|
| 5. Function (0) | 2024.03.14 |
| 4. Conditionals and Loops (0) | 2024.03.14 |
| 2. List, Set, Tuple (1) | 2024.03.14 |
| 1. Data Types (0) | 2024.03.14 |
