Note: error
and exception
are the same in Python.
Common Exception
- Exception Almost all the others are built off of it.
- AttributeError Raised when an attribute reference or assignment fails.
- IOError Raised when an I/O operation (e.g. a print statement, the built-in
open()
functio or a method of a file object) fails for an I/O-related reason, e.g. “file not found” or “disk full”. - ImportError Raised when an import statement fails to find the module definition or when a
from ... import
fails to find a name that is to be imported. - IndexError Raised when a sequence subscript is out of range.
- KeyError Raise when a mapping (dictionary) key is not found in the set of existing keys.
- KeyboardInterrupt Raised when the user hits the interrupt key (Ctrl+c or Del).
- NameError Raised when a local/global name is not found.
- OSError Raised when a function returns a system related error.
- SyntaxError Raised when the parser encounters a syntax error.
- TypeError Raised when an operation or function is applied to an object of inappropriate type. The associated value is string details about the type mismatch.
- ValueError Raise when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as
IndexError
. - ZeroDivisionError Raised when the second argument of a division or modulo operation is zero.
How to handle Exceptions
try:
1/0
except ZeroDivisionError:
print('You cannot divide by zero.')
# KeyError
my_dict = {'a' : 1, 'b' : 2, 'c' : 3}
try:
value = my_dict['d']
exception KeyError:
print('That key does not exist!')
# IndexError
my_list = [1, 2, 3]
try:
my_list[5]
except IndexError:
print('Index out of range.')
# A standard way to catch multiple exceptions
my_dict = {'a' : 1, 'b' : 2, 'c' : 3}
try:
value = my_dict['d']
except IndexError:
#pass
except KeyError:
#pass
except KeyError:
#pass
except:
#pass
Bare Excepts
# This is NOT recommended!
try:
1/0
except:
print('...')
The finally
Statement
You can use the finally
statement to clean up after yourself. You would also put the exit code at the end of the finally
statement.
my_dict = {'a' : 1, 'b' : 2, 'c' : 3}
try:
value = my_dict['d']
except KeyError:
# pass
finally:
# pass
try/except
, or else
The else
will only run if there are no errors raised.
my_dict = {'a' : 1, 'b' : 2, 'c' : 3}
try:
value = my_dict['d']
except KeyError:
# pass
else:
print('NO error occurred!')
finally:
print('....')
The only good usage of else
statement is where you want ot execute a second piece of code that can also raise an error. Of course, if an error is raised in the else
, it won’t get caught.