Learn Simpli

Free Online Tutorial For Programmers, Contains a Solution For Question in Programming. Quizzes and Practice / Company / Test interview Questions.

Exception handling in python

In this chapter, you will learn about exception handling in python. In every programming language, it’s common, that we get some error while running applications. Exception handling is a mechanism that handles an error in run time, for example, divide by zero is a kind error, which can happen at run time. Let’s look at how python helps in error handling.

What is an exception in software?

Exception:
An exception is an event which may be in an abnormal condition, for exception divide by zero
An exception occurs during the execution of a program when an unexpected event happens and it interrupts the normal flow of the program’s instructions at run time.

What is exception handling in software?

Exception handling:
Exception handling is a special process that handles an error in run time
Exception handling ensures that the flow of the program doesn’t break when an exception occurs
In simple words, we can use exception handling to let the script continue with other code, even the error occurs

Python supports the following keywords for exception handling.
try:
The try block contains the code that is attempted, this code may lead to an error
except:
The except block contains the code which will be executed if there is an error in the try block
finally:
The final block contains the code which will be executed regardless of any error

Let’s write an example of how to use exception handling mechanisms with the keywords try, except, finally. We are writing a program that accepts the input from the user and prints it. If the user enters the string then an error message will be printed.

while True:
    try:
        age = int(input("Please enter your age: "))
        print(f'Hi your age: {age}')
    except ValueError:
        print("Please enter valid age...")
        continue
    else:
        break
else:
    print("Closing the session...")

# output
# Please enter your age: age
# Please enter valid age...
# Please enter your age: name
# Please enter valid age...
# Please enter your age: 20
# Hi your age: 20

Exception handling in python code snippet

Exception handling in python code snippet examples

One thought on “Exception handling in python

Comments are closed.