Exceptions in Python

Posted by PythonStacks on October 20, 2020

 Python uses special objects called exceptions to manage errors that arise during a program’s runtime.

Whenever an error occurs that makes Python unsure what to do next, it creates an exception object. If you write code that handles the exception, the program will continue running. If you don’t
handle the exception, the program will halt and show a traceback, which includes a report of the exception that was raised.

 

Examples of code that results in an error

  • Trying to access a list index beyond its limit
    test = [1, 7, 4]
    test[4]                # IndexError
  • Trying to convert an inappropriate type
    int(test)               # TypeError
  • Referencing a non-existent variable
    print(a)          # NameError
  • Mixing data types without casting
    print("a"/4)            # TypeError

 

Other Types of Exceptions

  • SyntaxError      -     Python can't parse program
  • NameError       -    Local or global name not found
  • AttributeError    -    Attribute reference fails
  • TypeError          -    operand doesn't have a correct type
  • ValueError       -      operand type okay, but value type is wrong
  • IOError             -      Input-Output system reports malfunction
  • ZeroDivisionError -  Can't divide by 0

 

a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
print(a/b)

This program performs a division of two numbers provided by the User as Input. Just to demonstrate errors/exceptions, assuming the user inputs 5 and 0 as the first and second numbers respectively, python generates a ZeroDivisionError : 

Enter the first number: 5
Enter the second number: 0
Traceback (most recent call last):
  File "exceptions.py", line 3, in <module>
    print(a/b)
ZeroDivisionError: division by zero

 

 

Handling Exceptions In Python

Python provides handlers for exceptions. Exceptions are handled with try-except blocks.

A try-except block asks Python to do something, but it also tells Python what to do if an exception is raised. When you use try-except blocks, your programs will continue running even if things start to go wrong. Instead of tracebacks, which can
be confusing for users to read, users will see friendly error messages that you write.

 

try:
    a = int(input("Enter the first number: "))
    b = int(input("Enter the second number: "))
    print(a / b)
except:
    print("Bug in User Input")

Let's try provide the same input as before using 5 and 0 :

Enter the first number: 5
Enter the second number: 0
Bug in User Input

Providing a string as an input instead of a number :

Enter the first number: 5
Enter the second number: four
Bug in User Input

 

Previously the division of 5 and 0 results in a ZeroDivisionError.

It's the same here but we are telling Python that if there is an exception raised including ZeroDivisionError, it should print out Bug in User Input.

 

Providing the correct Input using 5 and 2 :

Enter the first number: 5
Enter the second number: 2
2.5

 The statement "Bug in User Input" is not printed because no error is raised here.

 


 

Handling specific exceptions

Though we can tell python to do something if any exception or error rises, it is more efficient telling python to execute something if a particular or specific exception is raised.

In the Division program above, we could rewrite it handling only the ZeroDivisionError  :

try:
    a = int(input("Enter the first number: "))
    b = int(input("Enter the second number: "))
    print(a / b)
except ZeroDivisionError:
    print("Can't divide by zero")

 

Taking User input to be 5 and 0:

Enter the first number: 7
Enter the second number: 0

Can't divide by zero

"Can't divide by zero"   is printed because a ZeroDivisionError is raised.

 

Taking User input to be 6 and  two:

Enter the first number: 6
Enter the second number: two

Traceback (most recent call last):
  File "exception.py", line 3, in <module>
    b = int(input("Enter the second number: "))
ValueError: invalid literal for int() with base 10: 'two'

Python raises an exception error because we have not written code for this particular exception i.e ValueError.

 

 


Share This Post

Tweet Share Share Share

Subscribe to receive updates!

0 Comments

Leave a comment

* Email would not published