PCAP Study notes - Exceptions
| 1 min read
Exceptions
All Exceptions are derived from BaseException
Concrete Exceptions
In Python, "concrete exceptions" refer to specific, built-in exception types that are raised by the interpreter or standard library functions in response to various error conditions. These contrast with more general exception types (like Exception itself) or user-defined exceptions.
Examples:
- TypeError
- Class methods or functions will raise a
TypeError
when called without the correct amount of positional arguments.
- Class methods or functions will raise a
"hello" + 5 # Raises TypeError; string and int types cannot be added
import math
math.pow(2) # Raises TypeError
- ValueError
int("abc") # Raises ValueError for incompatible value being passed to int()
- IndexError
my_list = [1,2,3]
my_list[5] # Raises IndexError
- KeyError
my_dict = {'a': 1}
my_dict['b'] # Raises KeyError
- NameError
print(not_defined_variable) # Raises NameError
- ZeroDivisionError
10 / 0 # Raises ZeroDivisionError
- FileNotFoundError
with open('non_existent_file.txt', 'r') as fp: # Raises FileNotFoundError
pass
- AttributeError
my_str = "this is some text"
my_str.non_existent_method() # Raises AttributeError
- ImportError
import non_existent_module # Raises ImportError