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:
1 | try: |
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:
1 | def main(): |
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.
1 | raise NameError('HiThere') |
---------------------------------------------------------------------------
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.
1 | try: |
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.
1 | try: |
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.
1 | try: |
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.
1 | class FileTypeError(Exception): |
---------------------------------------------------------------------------
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?