Exception Handling in Python

Exception handling in Python programming consist of three keywords try, throw, and catch. Exception handling provides a way to transfer control from one part of a program to another.

General form of Exceptions


try:
   You do your operations here
except ExceptionI:
   If there is ExceptionI, then execute this block
except ExceptionII:
   If there is ExceptionII, then execute this block
else:
   If there is no exception then execute this block

Program Using Exception

Program

x = 5
y = 0
try: #trying to execute.
    z = x/y #dividing and assigning to 'z' if equal to Zero then
    print("This Will Not Printing")
except BaseException as e: #catch Error 'e' is object, and
    print("The Exception is: ", e) #print this.
#U also write like 'except Exception as e:'.
Output
The Exception is: division by zero

Program Using Exception Another Program

Program

while True: #executing Loop.
    try: #trying to execute the program.
        x = int(input("Please Enter a Number: ")) #if user enter correct
        print("You entered correct: ", x)
        break #than Break the process, if not than
    except Exception as ex: #catching Exception and printing.
        print("The Exception is: ", ex)
Output
Please Enter a Number: abc
The Exception is: invalid literal for int() with base 10: 'abc'
Please Enter a Number: 56
You entered correct: 56

Using Exception Program
Program

while True: #executing Loop.
    try: #trying to execute the program.
        x = int(input("Please Enter a Number: ")) #if user enter correct
        break #than Break the process, if not than
    except: #catching Exception and printing.
        print("You Must Enter Integers")
Output
Please Enter a Number: bilal
You Must Enter Integers
Please Enter a Number: abc43
You Must Enter Integers
Please Enter a Number: 54
You entered correct: 54