Try and Except: Exception Handling in Python

In this article, I will introduce you to the concept of Exception Handling using Try and Except in the Python programming language.

Relying on user input from the input function means that you are not controlling what input into your program the user makes, and that input can cause an error.

Also, Read – Machine Learning Full Course for free.

For example, let’s say you write a program that collects two numbers from a user and prints the result of the first number divided by the second number:

type a number:
10
type another:
5
2

Exception Handling in Python using Try and Except:

Your program seems to be working. However, you will run into an issue if the user enters 0 as the second number:

type a number:
10
type another:
0
ZeroDivisionError: integer division or modulo by zero

You can’t just hope that someone using this program won’t enter 0 as the second number.

One way to solve this problem is to use exception handling, which allows you to test for error conditions, “catch” exceptions if they occur, and decide how to proceed.

The keywords try and except are used for exception handling. When you modify this program to use exception handling, if a user enters 0 as the second number, instead of raising an exception, the program may print a message telling them not to enter 0.

The try clause contains the error that could occur. The except clause contains code that will only execute if the exception in your try clause occurs. Here is an example of how you can use exception handling in your program, so if a user enters 0 as the second number, your program does not stop:

type a number:
10
type another:
0
b cannot be zero.

If the user enters anything other than 0 for b, the code in the try block executes and the except block does nothing. If the user enters 0 for b, instead of throwing an exception, the code in your except block is executed and your program prints b cannot be zero.

Hope you liked this article on the concept of handling exceptions using try and except in the Python programming language. Please feel free to ask your valuable questions in the comments section below.

Aman Kharwal
Aman Kharwal

I'm a writer and data scientist on a mission to educate others about the incredible power of data📈.

Articles: 1501

Leave a Reply