An exception is an error that occurs during execution of a program, sometimes called a runtime error. This could be a “file not found” error if you are trying to load a file that doesn’t exist, or a “type error” if you type text into a field when the program is expecting a number.
Exceptions are useful for handling errors encountered with file handling, network access, and data input.
These errors can be handled gracefully using Python’s exception handling procedures.
Types of Exception
Built in Python Exceptions
Exception | Cause |
---|---|
AssertionError | Raised when assert statement fails |
AttributeError | Raised when attribute assignment or reference fails |
EOFError | Raised when the input() function hits end-of-file condition |
FileNotFoundError | Raised when a file or directory is requested but doesn’t exist. Corresponds to errno ENOENT |
FloatingPointError | Raised when a floating point operation fails |
GeneratorExit | Raised when a generator's close() method is called |
ImportError | Raised when the imported module is not found |
IndexError | Raised when index of a sequence is out of range |
KeyError | Raised when a key is not found in a dictionary |
KeyboardInterrupt | Raised when the user hits interrupt key (Ctrl+C or delete) |
MemoryError | Raised when an operation runs out of memory |
NameError | Raised when a variable is not found in local or global scope |
NotImplementedError | Raised by abstract methods |
OSError | Raised when system operation causes system-related error |
OverflowError | Raised when result of an arithmetic operation is too large to be represented |
ReferenceError | Raised when a weak reference proxy is used to access a garbage collected referent |
RuntimeError | Raised when an error does not fall under any other category |
StopIteration | Raised by next() function to indicate that there is no further item to be returned by iterator |
SyntaxError | Raised by parser when syntax error is encountered |
IndentationError | Raised when there is incorrect indentation |
TabError | Raised when indentation consists of inconsistent tabs and spaces |
SystemError | Raised when interpreter detects internal error |
SystemExit | Raised by sys.exit() function |
TypeError | Raised when a function or operation is applied to an object of incorrect type |
UnboundLocalError | Raised when a reference is made to a local variable in a function or method, but no value has been bound to that variable |
UnicodeError | Raised when a Unicode-related encoding or decoding error occurs |
UnicodeEncodeError | Raised when a Unicode-related error occurs during encoding |
UnicodeDecodeError | Raised when a Unicode-related error occurs during decoding |
UnicodeTranslateError | Raised when a Unicode-related error occurs during translating |
ValueError | Raised when a function gets argument of correct type but improper value |
ZeroDivisionError | Raised when second operand of division or modulo operation is zero |
Whenever an exception occurs, the interpreter halts the execution of the program and raises an exception error as shown in the table.
You can catch these exceptions using the try and except keywords and provide code to handle the error.
Catching Exceptions
If we run the following code , the Python interpreter will raise a FileNotFoundError exception because there is no file called “file.txt”. This will cause the program to crash.
The try block contains the code to execute. The except block contains the code to handle the error.
Let’s take a look at the program again. We can take our code and place it in the “try’” block. Then add an “except” block to deal with the error. If we look at the error message in the shell, we see this is a FileNotFoundError. We can add this after the “except” keyword.
Now, when we run the program, we get a simple message rather than an ugly error.
Raising Your Own Exceptions
Here in the file raise.py, we’ve raised a ValueError exception .
Summary
An exception is an error that occurs during execution of a program, sometimes called a runtime error.
You can catch exceptions using the try and except keywords.