logo codesdope

Exception Handling in Python


Till now, you have written a lot of codes in Python. But the codes were not yet ready to handle errors. For example, take a case when a user enters a negative value to a factorial program, our code will not throw any error but a negative value is definitely not a valid input for the calculation of factorial and hence, we will get a wrong result. One way to handle this situation would be to use if/else clause but Python provides a different tool specifically to handle errors. So, let’s learn about that.

We use try and except to handle errors in Python. The code which we want to execute is written inside try. If the statements inside the try have any error, then the statement inside the except block is executed. Let’s have a look at some examples.

  • Python 2
  • Python 3
try:
    print "Hello World"
except:
    print "Some Error Occurred!"
try:
    print("Hello World")
except:
    print("Some Error Occurred!")
Output
Hello World

As you can see that there was no error in the statement inside the try block, so it executed successfully and the statement inside the except block didn’t execute.

Let’s have an example with some error and see what happens.

  • Python 2
  • Python 3
try:
    print "Hello World"
    a = raw_input()
    a = int(a)
    print a//2
except:
    print "Some Error Occurred!"
try:
    print("Hello World")
    a = input()
    a = int(a)
    print(a//2)
except:
    print("Some Error Occurred!")
Output
abc
Some Error Occurred!

There is no syntax error in our code, so our code got executed. Also, there is no error in the first two statements of the try, so they were executed successfully. But we have given “abc”, a string as our input and the statement int(a) will produce an error if the value of a is a string. Thus, the statement of except print("Some Error Occurred!") got executed and “Some error Occurred!” got printed.

Using else with try except


We can also use else with try and except. The statements of else are executed if the code is executed without any error i.e. when the except block is not executed. Let’s have a look at an example.

  • Python 2
  • Python 3
try:
    a = input()
    print a//2
except:
    print "Some Error Occurred!"
else:
    print "No Errors!"
try:
    a = input()
    a = int(a)
    print (a//2)
except:
    print("Some Error Occurred!")
else:
    print("No Errors!")
Output
12
6
No Errors!

You can try different inputs with this code and can see that the statement of except will be executed in case of errors and in the case of successful execution i.e., in case not execution of the except block, the statement of else will be executed.

Finally


When we have codes which we want to get executed in any case i.e., regardless of execution of try or except block, we write those codes in the finally block. Let’s look at an example.

  • Python 2
  • Python 3
try:
    a = input()
    print a//2
except:
    print "Some Error Occurred!"
finally:
    print "Either of try or except is executed."
try:
    a = input()
    a = int(a)
    print (a//2)
except:
    print("Some Error Occurred!")
finally:
    print("Either of try or except is executed.")
Output
e
Some Error Occurred!
Either of try or except is executed.
  • Python 2
  • Python 3
try:
    print "Hello!"
except:
    print "There is an error."
else:
    print "No error."
finally:
    print "End of code."
try:
    print("Hello!")
except:
    print("There is an error.")
else:
    print("No error.")
finally:
    print("End of code.")
Output
Hello!
No error.
End of code.

Before proceeding further, let’s have a look at the types of error in Python.

Errors in Python


We can broadly classify errors into two categories - Syntax Error and Exception Errors.

Syntax Errors → This occurs when there is a wrong syntax in our code.

Exception Errors → When there is no syntax error in our code and our code gets executed but some error occurs during the execution, then this type of error is called Exception Error. For example, in the above examples the errors raised by the string input were exception errors, dividing a number with 0 is also an exception error, etc.

Some of the common exceptions are:

  • IOError → When an I/O (input/output) operation fails. For example, error while opening a file, etc.
  • KeyboardInterrupt → This occurs when a user interrupts the keyboard i.e., by pressing control+C or Delete key.
  • ValueError → When an operation or functions argument of right type but of inappropriate value.
  • EOFError → When input() hits end-of-file condition (EOF) without reading any data.
  • ImportError → When import statement is not able to load a module.
  • ZeroDivisionError → Raised when the second argument of a division or modulo operation is zero.
  • IndexError → Raised when a sequence subscript is out of range.
  • NameError → Raised when a local or global name is not found.
  • OverflowError → Raised when the result of an arithmetic operation is too large to be represented.
  • TypeError → Raised when an operation or function is applied to an object of inappropriate type.

You can see the entire list of exceptions from Python’s Official Documentation.

Handling Specific Exception


Till now, we were dealing with errors with except and it was dealing with all types of exceptions. But we can also deal with different exceptions differently. For example, we can make an except block to deal only with ZeroDivisionError.

To make an except block to deal with a specific exception, we write except TypeOfException. Here, TypeOfException is the type of the exception which we want to catch in this except block. Let’s look at an example.

  • Python 2
  • Python 3
try:
    print 5/0
except ZeroDivisionError:
    print "Division by 0 is not permitted."
try:
    print(5/0)
except ZeroDivisionError:
    print("Division by 0 is not permitted.")
Output
Division by 0 is not permitted.

As you can see, we have caught ZeroDivisionError in the above example.

Handling Multiple Exceptions


We can also have multiple except block as shown in the example given below.

  • Python 2
  • Python 3
def divide(a, b):
    try:
        print a//b
    except TypeError:
        print 'Check the type of arguments.'
    except ZeroDivisionError:
        print 'Error: Division by 0'
    except:
        print 'Unknown Error'

print "5/\'2\'"
divide(5, '2')
print ''

print "5/0"
divide(5, 0)
print ''

print '5/2'
divide(5, 2)
def divide(a, b):
    try:
        print(a//b)
    except TypeError:
        print('Check the type of arguments.')
    except ZeroDivisionError:
        print('Error: Division by 0')
    except:
        print('Unknown Error')

print("5/\'2\'")
divide(5, '2')
print('')

print("5/0")
divide(5, 0)
print('')

print('5/2')
divide(5, 2)
Output
5/'2'
Check the type of arguments.

5/0
Error: Division by 0

5/2
2

Handling Multiple Exceptions in Single Except Block


We can also handle multiple exceptions in a single except. We just write the types of errors which want to handle with the except in a tuple. This is shown in the example given below.

  • Python 2
  • Python 3
def divide(a, b):
    try:
        print a//b
    except (TypeError, ZeroDivisionError):
        print 'Check type of arguments and make sure you are not dividing by 0.'

print "5/\'2\'"
divide(5, '2')
print ''

print "5/0"
divide(5, 0)
print ''

print '5/2'
divide(5, 2)
def divide(a, b):
    try:
        print(a//b)
    except (TypeError, ZeroDivisionError):
        print('Check type of arguments and make sure you are not dividing by 0.')

print("5/\'2\'")
divide(5, '2')
print('')

print("5/0")
divide(5, 0)
print('')

print('5/2')
divide(5, 2)
Output
5/'2'
Check type of arguments and make sure you are not dividing by 0.

5/0
Check type of arguments and make sure you are not dividing by 0.

5/2
2

Using as keyword


We can also get the exact exception which is occurring using the as keyword. It is shown in the example given below.

  • Python 2
  • Python 3
try:
    print(5//0)
except ZeroDivisionError as ex:
    print(ex)
try:
    print(5//0)
except ZeroDivisionError as ex:
    print(ex)
Output
integer division or modulo by zero

Raising Errors


We can also raise an error anytime we want using the raise keyword. Let’s see it working.

  • Python 2
  • Python 3
raise ZeroDivisionError
raise ZeroDivisionError
Output
Traceback (most recent call last):
  File "b.py", line 1, in <module>
    raise ZeroDivisionError
ZeroDivisionError
  • Python 2
  • Python 3
raise IndexError('Index is out of the range.')
raise IndexError('Index is out of the range.')
Output
Traceback (most recent call last):
  File "b.py", line 2, in <module>
    raise IndexError('Index is out of the range.')
IndexError: Index is out of the range.


# Further Readings

Doubt? Ask question
Close

Welcome.please sign up.

Close

Welcome.please login.