avatar

目录
python exception basics

Catch built-in type exceptions

simple non-inspect exception

For the following example, ‘myfile.txt’ does not exist. Therfore, the exception will trigger the code that is defined under the except block. Code will not stop but continue. The code under try block will be just ignored. Example below:

python
1
2
3
4
5
6
7
try:
f = open('myfile.txt')
except Exception as e:
print("Unexpected error:", sys.exc_info())
print(e.__class__)
print(e.__str__())
print("code continues")
Unexpected error: (<class 'FileNotFoundError'>, FileNotFoundError(2, 'No such file or directory'), <traceback object at 0x0000022951A150C8>)
<class 'FileNotFoundError'>
[Errno 2] No such file or directory: 'myfile.txt'
code continues

The sys.excinfo() will have the exit information for what class the exception is. The format is: type, value, object

The e._class\
and e.__str()__are exception class methods which contain the exception class name and printing out information.

The print out of ‘code continues’ indicates that the try block code is ignored and program does not exit.

I would think this type of exception handling will be used for the main function only, as any other exception which we don’t want to handle by ourselves has no need to have additional logic. Example below:

python
1
2
3
4
5
6
def main():
try:
create_logdir()
except Exception as e
logging.exception(e)
raise

raise an exception intentionally

By raising the exception, the correspoding method of build-in exception will be called. IDE will stop and not run the remaining code.

python
1
2
raise NameError('HiThere')
print('Continue code')
---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

<ipython-input-17-ecb1af770a0f> in <module>()
----> 1 raise NameError('HiThere')
      2 print('Continue code')


NameError: HiThere

If putting a raise at the bottom, after the execution of the code you define, the handler method from above exception object method will be triggered. See below.

python
1
2
3
4
5
6
try:
f = open('myfile.txt')
except Exception:
print("Unexpected error:", sys.exc_info())
raise
print("code continues")
Unexpected error: (<class 'FileNotFoundError'>, FileNotFoundError(2, 'No such file or directory'), <traceback object at 0x000001E05FC58D48>)



---------------------------------------------------------------------------

FileNotFoundError                         Traceback (most recent call last)

<ipython-input-18-bc5f8ae109ca> in <module>()
      1 try:
----> 2     f = open('myfile.txt')
      3 except Exception:
      4     print("Unexpected error:", sys.exc_info())
      5     raise


FileNotFoundError: [Errno 2] No such file or directory: 'myfile.txt'

If you want to simply print or log the message for the exception, you can print or log the exception object.

The string that is printed out is the return from_str_ build-in method.
Again, the raise at the bottom of except block will make sure the exception instance handler is called.

python
1
2
3
4
5
6
7
try:
f = open('myfile.txt')
except Exception as e:
print("Unexpected error:", e)
print("Unexpected error:",e.__str__())
raise
print("code continues")
Unexpected error: [Errno 2] No such file or directory: 'myfile.txt'
Unexpected error: [Errno 2] No such file or directory: 'myfile.txt'



---------------------------------------------------------------------------

FileNotFoundError                         Traceback (most recent call last)

<ipython-input-16-b337c26a5c69> in <module>()
      1 try:
----> 2     f = open('myfile.txt')
      3 except Exception as e:
      4     print("Unexpected error:", e)
      5     print("Unexpected error:",e.__str__())


FileNotFoundError: [Errno 2] No such file or directory: 'myfile.txt'

specify special handling for each exception type

Below is an example of catching different built-in type of exceptions.

python
1
2
3
4
5
6
7
8
9
10
11
12
13
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except OSError as err:
print("OS error: {0}".format(err))
raise
except ValueError:
print("Could not convert data to an integer.")
raise
except:
print("Unexpected error:", sys.exc_info()[0])
raise
OS error: [Errno 2] No such file or directory: 'myfile.txt'



---------------------------------------------------------------------------

FileNotFoundError                         Traceback (most recent call last)

<ipython-input-70-778921e79d26> in <module>()
      1 try:
----> 2     f = open('myfile.txt')
      3     s = f.readline()
      4     i = int(s.strip())
      5 except OSError as err:


FileNotFoundError: [Errno 2] No such file or directory: 'myfile.txt'

Custom Exception

I would use custom exception to define API errors that are not inclued in python built-in exceptions. Example below.

python
1
2
3
4
5
6
7
class FileTypeError(Exception):
def __init__(self):
# log something here
Exception.__init__(self,"well, you type is wrong, isn't it?")
some_condition = True
if (some_condition):
raise FileTypeError
---------------------------------------------------------------------------

FileTypeError                             Traceback (most recent call last)

<ipython-input-95-1a7136f7f775> in <module>()
      5 some_condition = True
      6 if (some_condition):
----> 7     raise FileTypeError


FileTypeError: well, you type is wrong, isn't it?

评论