Python Try Catch Exceptions Tutorial


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 problem 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 who 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 myapp.py .

#!/usr/bin/python3 
 
num1 = input ("Enter number") 
 
print(num1*num1)

When we call our application like below by providing a character like othera then a number we will get an exception.

$ python3 myapp.py
What is An Exception
What is An Exception

We also get the exception type. Python provides a different type of exceptions for different situations. In this code the exception type is TypeError .

Exception Types

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 is a base class and exception for all built-in exceptions except StopIteration and SystemExit.
  • ArithmeticError is a 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 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 to 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 does not suit any specific category.
  • NotImplementedError exception raised when an abstract method that is not implemented tried to be used.
LEARN MORE  JavaScript "Uncaught TypeError: Cannot set property '...' of null " Error Solutions

Catch An Exception with Try and Except

Now we want to prevent this type of bugs and exceptions programmatically. Python provides a mechanismtry which is used to detect exceptions in the given block of the code. We will put the potential error block into liketry below. Here we guess that lineprint(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 ita will not raise an exception. It simply skips to the codeexcept block which will run if an exception is raised. Then the application will flow in a normal situation.

Handle An Exception with Try and Except
Handle An Exception with Try and Except

Catching Specific Exceptions

In the previous example, we have fired a single type of exception with the codeexcept block. But we can catch a specific type of exception and ignoring others. As we remember from the first example we get the exceptionTypeError. If we only need to catch an exceptionTypeError and ignore others we will specify toTypeError the likeexcept below.

#!/usr/bin/python3 
 
num1 = input ("Enter number") 
 
try: 
   print(num1*num1) 
 
except TypeError: 
   print("An TypeError occurred") 
 
 
print("Operation completed")
Catching Specific Exceptions
Catching Specific Exceptions

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 to 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 the 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 TypeError and ZeroDivisionError .

#!/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 try-except blocks finally, the code block will be run. This is generally used to release resources like file, database connection, or revert operations used in try code block.

LEARN MORE  Python "with" Statement By Examples

In this example, we will close file-handle in the finally code block whether previous code blocks work or raise an exception.

#!/usr/bin/python3 
 
try: 
   f = open("personels.txt") 
   f.read() 
 
finally: 
   f.close()

Raise Exception

Up to now, we have handled self-raised exceptions. We can also raise an exception manually without waiting for a user to input any change. We will use keywordraise in order to raise an exception manually. In this example, we will raise typeZerrorDivisionError exception.

#!/usr/bin/python3 
 
try: 
   print("0/0") 
   raise ZeroDivisionError 
 
except (ZeroDivisionError): 
   print("An ZeroDivisionError occurred") 
 
 
print("Operation completed")
Raise Exception
Raise Exception

User-Defined Exceptions

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 operations for files. We can define our own user-defined exceptions by using classRuntimeError like below. We will put the following code into CorpExceptions.py

#!/usr/bin/python3 
 
class InvalidMove(RuntimeError): 
   def __init__(self, arg): 
      self.args = arg

and we can raise as we did before after importing CorpExceptions.py

raise InvalidMode

Leave a Comment