As a developer, we have a lot of thoughts about the applications and features. Implementing them a tedious task. During the implementation, we can make mistakes. Those mistakes can be related to applications logic or technical. These errors will cause problems while the application is running. We call this type of problems as exceptions. We can not prevent all exceptions but we can create some mechanisms to handle these situations. In this tutorial, we will look at how to handle these exceptions.
What is An Exception
Some of us may be familiar with exceptions but there may be others those do not have any idea about exceptions. Exceptions are unexpected error situations where applications generally stop working. Sometimes it will not stop working but will not work properly either.
Here is an example of how an exception occurs. Our applications get input from the user and multiple given numbers. But there will be an exception if the user inputs string. The filename is
#!/usr/bin/python3 num1 = input ("Enter number") print(num1*num1)
When we call our application like below by providing a character like other
a then a number we will get an exception.
$ python3 myapp.py
We also get the exception type. Python provides a different type of exceptions for different situations. In this code the exception type is
As there are a lot of different libraries and function there is a different type of exceptions. Here some of the most popular of them.
- `Exception` is the generic and base class for all exceptions
- `StopIteration` exception raised when the next() method of an iterator does not point to any object.
- `SystemExit` exception raised by the sys.exit() function.
- `StandardError` exception is a base class and exception for all built-in exceptions except StopIteration and SystemExit.
- `ArithmeticError` exception is base class for all error that occurs during mathematical and arithmetic calculations and operators
- `OverFlowError` exception raised when calculation exceeds the maximum limit for given numerical type.
- `ZeroDivisionError` exception raised when a division or modulo by zero takes place for numerical operations.
- `AssertionError` raised in case of failure of the assert Python programming language statement.
- `AttributeError` exception raised in case of failure of attribute reference or assignment.
- `EOFError` exception raised when there is no input or the end of a file is reached.
- `ImportError` exception raised when an import Python programming language statement fails.
- `KeyboardInterrupt` exception raised when the user interrupts the execution of the application with Linux kill command or pressing CTRL+C keyboard shortcut.
- `LookupError` exception raised for all lookup errors.
- `IndexError` exception raised when an index is not found in the array, list in a sequence.
- `KeyError` exception raised when the specified key is not found in the dictionary.
- `NameError` exception raised when an identifier is not found in the local or global namespace.
- `UnboundLocalError` exception raised when trying to access a local variable in a function, method, module but no value has been assigned to it.
- `EnvironmentError` exception is based class for all exceptions that occur outside of the Python Environment.
- `IOError` exception raised when an input/output operations fail, such as writing a file failed or a file can not be opened.
- `SyntaxError` exception raised when there is an error related with the Python Syntax.
- `IndentationError` exception raised when indentation is not specified and used properly to catch code block.
- `SystemError` exception raised when the Python interpreter finds and internal problem.
- `TypeError` exception raised when an operation, function, method is attempted to get, set different type of variable or data type.
- `ValueError` exception raised when built-in function fora data type has the valid type of arguments, but the arguments have invalid values.
- `RuntimeError` exception raised when the raised exception or error do not suit any specific category.
- `NotImplementedError` exception raised when an abstract method which is not implemented tried to be used.
Catch An Exception with Try and Except
Now we want to prevent this type of bugs and exceptions programmatically. Python provides a mechanism
try which is used to detect exceptions in the given block of the code. We will put the potential error block into like
try below. Here we guess that line
print(num1-num1) can raise an exception.
#!/usr/bin/python3 num1 = input ("Enter number") try: print(num1*num1) except: print("An error occured") print("Operation completed")
When we run by providing a character like it
a will not raise an exception. It simple skip to the code
except block which will run if an exception is raised. Then the application will flow in a normal situation.
Catching Specific Exceptions
In the previous example, we have fired a single type of exception with the code
except block. But we can catch a specific type of exception and ignoring others. As we remember from the first example we get the exception
TypeError. If we only need to catch an exception
TypeError and ignore others we will specify to
TypeError the like
#!/usr/bin/python3 num1 = input ("Enter number") try: print(num1*num1) except TypeError: print("An TypeError occurred") print("Operation completed")
Else If No Exception Raised
We generally expect to raise some exception while running critical code. But in some cases, there will be no error or exception. We can define some code to execute if there is no error and exception with the
else keyword. We will put the code we want to run if there is no error or exception inside
else keyword block. In this example, we will print screen “There is no exception” if there is no error or exception.
#!/usr/bin/python3 num1 = input ("Enter number") try: print(num1*num1) except TypeError: print("An TypeError occurred") else: print("There is no exception") print("Operation completed")
Catch Multiple Type Exceptions
We may need to catch multiple exceptions in a single
except code block. We will provide the exception types in brackets by separating them with command
(TypeA , TypeB , TypeC , ...)
In this example we will catch both
#!/usr/bin/python3 num1 = input ("Enter number") try: print(num1*num1) except (TypeError,ZeroDivisionError): print("An TypeError occured") print("Operation completed")
Run Code After Exception with Finally
While checking exceptions in
try code block we may need to execute some come whatever happens even
try code block works or
except code block works. We will use
finally code block to complete the
try-except blocks. After the
finally code block will be run. This is generally used to release resources like file, database connection or revert operations used in
try code block.
In this example we will close file handle in the
finally code block whether previous codes blocks works or raise an exception .
#!/usr/bin/python3 try: f = open("personels.txt") f.read() finally: f.close()
Up to now, we have handled self-raised exceptions. We can also raise an exception manually without waiting for a user input other any change. We will use keyword
raise in order to raise an exception manually. In this example, we will raise type
#!/usr/bin/python3 try: print("0/0") raise ZeroDivisionError except (ZeroDivisionError): print("An ZeroDivisionError occurred") print("Operation completed")
While programming enterprise applications and libraries we will need to create our exception type library too. We may need to provide operational exceptions like invalid move operation for files. We can define our own user-defined exceptions by using class
RuntimeError like below. We will put the following code into
#!/usr/bin/python3 class InvalidMove(RuntimeError): def __init__(self, arg): self.args = arg
and we can raise as we did before after importing