Exception Handling in Python

Exceptions can be very bothering at times. Here’s where the concept of Exception Handling comes in. Through Exception Handling, we can easily handle the exceptions for the user instead of just throwing errors at the user.

Example : In this program, the input is taken in the type ‘int’. But if we enter a character in it, it will throw a ‘ValueError’. This can confuse the user a lot of times. Here’s where we do the Exception Handling. Instead of throwing value error and confuse the user, we will display a statement suggesting the user to try again and we will give a chance to the user to try inputting the numbers again.

Python3




num1 = int(input('Enter num1: '))
num2 = int(input('Enter num2: '))
answer = f'{num1} / {num2} = {num1 / num2}'
print(answer)


Output

Enter num1: 1
Enter num2: b
Traceback (most recent call last):
File "D:/PycharmProjects/pythonProject2/main.py", line 15, in <module>
num2 = int(input('Enter num2: '))
ValueError: invalid literal for int() with base 10: 'b'

Using try, except and else

In this code, the while loop is run because we want to let the user try until the input is given in the correct way.We have used the ‘try’ clause. The try clause checks for the errors in the lines in that clause.

If an exception is encountered, it jumps to the ‘except’ clause and prints the error message provided by us. We have written two except clauses, one with the ValueError and the other with the ZeroDivisionError. Each of these clauses deal with respective exceptions and print out the respective messages.

Then, lastly, we have written the else clause. If no error is encountered, the else block is executed. In the else block, we print the quotient of the division and break out from the loop.

Python3




while True:
    try:
        num1 = int(input('Enter num1: '))
        num2 = int(input('Enter num2: '))
        answer = f'{num1} / {num2} = {num1 / num2}'
    except ValueError as e:
        print('Try putting an integer value.\n Error Occured:', e)
    except ZeroDivisionError as ex:
        print('Division by zero is invalid!\n Error Occured:', ex)
    else:
        print(answer)
        break


Output:

Printing Exceptions

Now, as we have seen what exceptions exactly are, how do they look like and how to handle them, we will now have a look at printing them.

To print the Exceptions, we use ‘as’ keyword of Python.

We have used the same example that we used before. We have used the ‘as’ keyword and declared the variable ‘ve’ for ‘ValueError’ and ‘zde’ for ‘ZeroDivisionError’. Then, if we encounter any exceptions, we have written the code to print that exception. But still, we are not able to see the Type of Exception we got.

Python3




while True:
    try:
        num1 = int(input('Enter num1: '))
        num2 = int(input('Enter num2: '))
        answer = f'{num1} / {num2} = {num1 / num2}'
    except ValueError as ve:
        print(ve)
    except ZeroDivisionError as zde:
        print(zde)
    else:
        print(answer)
        break


Output:

Enter num1: a
invalid literal for int() with base 10: 'a'
Enter num1: 0
Enter num2: 0
division by zero
Enter num1: 16
Enter num2: 4
16 / 4 = 4.0

Printing Exception Type

To see the exception type, we can use the type() function.

Here we have used the type() function to know the type of exception we have encountered while running the code.

Python3




while True:
    try:
        num1 = int(input('Enter num1: '))
        num2 = int(input('Enter num2: '))
        answer = f'{num1} / {num2} = {num1 / num2}'
    except ValueError as ve:
        print(type(ve), ve)
    except ZeroDivisionError as zde:
        print(type(zde), zde)
    else:
        print(answer)
        break


Output

Enter num1: a
<class 'ValueError'> invalid literal for int() with base 10: 'a'
Enter num1: 1
Enter num2: 0
<class 'ZeroDivisionError'> division by zero
Enter num1: 4
Enter num2: 2
4 / 2 = 2.0



Python Print Exception

An Exception is an Unexpected Event, which occurs during the execution of the program. It is also known as a run time error. When that error occurs, Python generates an exception during the execution and that can be handled, which prevents your program from interrupting. In this article, we are going to focus on ‘How can we print an exception in Python?’

Similar Reads

What is Exception in Python?

In Python, Exception is a type of Error in the program. An Error is called an ‘Exception’ when the program is syntactically correct, but an error occurs while executing it....

Exception Handling in Python

...