Exception handling in Python

How to handle exception in Python? A Python program terminates as soon as it encounters an error. In Python, an error can be a syntax error or an exception. In this article, you will see what an exception is and how it differs from a syntax error. After that, you will learn about raising exceptions and making assertions. Then, you’ll finish with a demonstration of the try and except block.

Exception Handling

Consider a basic calculator, which can just divide numbers, where we approach a user for input of two numbers and afterward print the result.

while True:
   num_one = int(input("Enter the first number: "))
   num_two = int(input("Enter the second number: "))
   res = num_one / num_two
   print("The result of your division is: ", res)

Output

Now, let’s try the impossible

Again we experience this traceback which crashes our program totally! For preventing this, we have to utilize try-exception statements in the place, which can be a possible source of errors. Here it’s where we make division — the variable result, so let’s brace it with try-except blocks:

while True:
   num_one = int(input("Enter the first number: "))
   num_two = int(input("Enter the second number: "))
   try:
       res = num_one / num_two
   except ZeroDivisionError:
       print("You can not divide by zero!!")
   else:
       print("The result of your division is: ", res)
   finally:
       print("Thanks for using our calculator! Come again!")

Output

Exception handling keywords

Here you can see not only try and except keywords as well as else and finally. The full exception handling block performs as follows:

  • To begin with, Python executes the try block: everything between try and except.
  • If there is no exception, the try block is effectively executed and wrapped up.
  • If any chance an exception occurs, the rest of the try block is skipped. From that point onward, Python checks if the type of exception matches the exception indicated after the except keyword, it executes the except block and keeps executing the program after the try-except block.
  • If an exception doesn’t match the exception named in the except clause, it is called an unhandled exception, and execution of your program stops with a traceback.
  • The else-block in this circumstance is possibly executed if there happened no exceptions.
  • There can likewise be finally keyword. A final clause is always executed before leaving the try-except block, regardless of whether an exception has happened or not.

Now, let’s try our program with different inputs:

while True:
   num_one = int(input("Enter the first number: "))
   num_two = int(input("Enter the second number: "))
   try:
       res = num_one / num_two
   except ZeroDivisionError:
       print("You can not divide by zero!!")
   else:
       print("The result of your division is: ", res)
   finally:
       print("Thanks for using our calculator! Come again!")

Output

Raise an exception

As a Python developer you can choose to throw an exception if a condition occurs.

To throw (or raise) an exception, use the raise keyword.

num = 20

if(num > 10):
  raise Exception("Sorry, no numbers greater than ten")

Output

You can define what kind of error to raise, and the text to print to the user.

x = "Welcome to Disneyland"

if not type(x) is int:
  raise TypeError("Only integers are allowed")

Output

Handling several exceptions

But what if our user doesn’t understand what the “number” is and enters, for example, “one”?

Again we get an error since we indicated just a ZeroDivisionError exception in our try-except block. Furthermore, here we have a ValueError exception, so Python doesn’t have to deal with it in our program.

As all the built-in exceptions include a hierarchical structure, you can do the accompanying and identify no specific exception:

except:
   print("An error occurred! Try again.")

Accordingly, you’ll get an exception from the list. But, it will likewise work for KeyboardInterrupt and other valuable exceptions and moreover, it’s viewed as a bad tone in programming, so it’d be better to utilize at least two except blocks for various exceptions:

except ZeroDivisionError:
   print("You can't divide by zero!!")
except ValueError:
   print("You can only enter numbers consisting of digits, not text!!")

An except clause also may specify multiple exceptions as a parenthesized tuple, for example:

except (ValueError, TypeError):
   print("You can only enter numbers consisting of digits, not text!!")

Due to the hierarchical structure, one exception can actually catch multiple exceptions. For example:

except ArithmeticError:
    print("I will also catch FloatingPointError, OverflowError, and ZeroDivisionError")

Now and then there can be a circumstance in which you can’t predict the type of exception in your code. You have no other choice, but to utilize the most general exception:

except:
    # do your operation

you should use except Exception:

except Exception:
    # do your operation

except Exception contains all Python exception yet the accompanying three: GeneratorExit, KeyboardInterrupt, SystemExit. So if you utilize this structure, you will at present have the option to complete your program by the means of keyboards or commands, which cause SystemExit.

You can check all the built-in Python Exceptions here

Hence, we can conclude:

  • To deal with exceptions without terminating your program, Python has the try-except block.
  • There are two more blocks to expand the possibilities to change the behavior of a program: else, which will be executed only if there are no exceptions in try-block, and finally, which will be executed at the end of the try-except block whether the exception happened or not.
  • All the exceptions comprise a hierarchical structure, i.e. some exceptions also include other exceptions.
  • If you want to catch all possible exceptions, you should use the Exception construction.
  • Using those means smartly, you can write sustainable and effective code to prevent users’ mistakes and to keep your program running even under unexpected circumstances.

Let’s try to solve the problem:

Prevent ZeroDivisionError in the code below. When the denominator is 0, print the message “Division by zero is not supported”. In other cases, print n divided by denominator.

Sample Input 1:

100
1
Sample Output 1:

100
Sample Input 2:

3
0
Sample Output 2:

Division by zero is not supported

n = int(input())
denominator = int(input())
try:
    print(n // denominator)
except ZeroDivisionError:
    print("Division by zero is not supported")

Output 1

Output 2