Python Try Except
The try statement lets code to be executed without making a running program stop even if errors are occurred.
The except statement is where exceptions errors are handled when errors are occurred.
Errors are faults or mistakes in the program which can make a program behave abnormally when it is run. Errors in the code are also called bugs in the programming world.
Types of Errors
There are two types of errors:
- Syntax errors
- Exceptions
Syntax Errors
Syntax errors are also called parsing errors. This type of error occurs due to mistakes in code syntax.
Example
The following code shows Indent expected error on line 3:
x = 1
while x < 5:
x += 1
print(x)
The only solution to handle syntax errors is to write the code syntax correctly. The correct form of above code is:
x = 1
while x < 5:
x += 1
print(x)
Exceptions
Exceptions are errors which are occurred during execution of a program.
Example
This code will generate error because a value is not divisible by 0.
result = 5/0
print(result)
Handling Exceptions
Exceptions can be handled using the try expect statements.
Example
try:
result = 5/0
print(result)
except Exception as ex:
print("Exception occurred")
print(ex)
Handling Multiple Exceptions
A try statement may have multiple except clause for handling different exceptions.
Example
try:
result = 5 / 0
print(result)
except ZeroDivisionError:
print("Divide by zero error occurred")
except NameError:
print("Name Error occurred")
Built-in Exceptions
List of built-in exceptions in Python:
Exception | Cause of Error |
ArithmeticError | Raised when an arithmetic operation fails. |
AssertionError | Raised when an assert statement fails. |
AttributeError | Raised when an attribute referrence or assignment fails. |
EOFError | Raised when the built-in function input() or raw_input() hits end-of-file condition. |
FloatingPointError | Raised when a floating-point operation fails. |
GeneratorExit | Raised when a generator or coroutine is closed. |
ImportError | Raised when an import fails. |
IndexError | Raised when an trying to access index that is out of range. |
KeyError | Raised when trying to read a mapping key that does not exists in a set of existings keys. |
KeyboardInterrupt | Raised when a user presses the interrupt key (Crtl+C or Delete). |
MemoryError | Raised when the program runs out of memory. |
NameError | Raised when a variable is not found in global or local scope. |
NotImplementedError | Raised when overriding the abstract methods in a user-defined class. |
OSError | Raised due to system-related error return by system functions. |
OverflowError | Raised when the result of an arithmetic operation is too big. |
ReferenceError | Raised when a weak reference proxy is used to access the referent after the garbage collection. |
RuntimeError | Raised when an unspecified error occurs. |
StopIteration | Raised when an the built-in next() function is called to indicate that no item is left to be return by an iterator. |
SyntaxError | Raised when there is a syntax error. |
IndentationError | Raised due to incorrect identation in the code. |
TabError | Raised due to incorrect number of tabs and spaces. |
SystemError | Raised due to internal error in the Python interpreter. |
SystemExit | Raised when the sys.exit() function is called. |
TypeError | Raised due to inappropriate argument type. |
UnboundLocalError | Raised when a reference is made to a local variable that has not been assigned any value inside a method or function. |
UnicodeError | Raised when a Unicode related error occurs. |
UnicodeEncodeError | Raised when a Unicode encoding error occurs. |
UnicodeDecodeError | Raised when a Unicode decoding error occurs. |
UnicodeTranslateError | Raised when a Unicode-related error occurs during translation. |
ValueError | Raised when an argument of a function receives the value of another incorrect type. |
ZeroDivisionError | Raised when trying to divide a value by 0 |